<!DOCTYPE html><html lang="zh-CN"><head>    <meta charset="UTF-8">    <meta name="viewport" content="width=device-width, initial-scale=1.0">    <title>数智作业后台管理系统 - 首页</title>    <link rel="icon" href="/assets/ico/7favicon.png" type="image/png">    <script src="https://cdn.tailwindcss.com"></script>    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">    <link href="/assets/css/main.css" rel="stylesheet">
    <script src="/js/api.js"></script>
    <style>
        /* 全局样式 */
        body {
            font-family: "Segoe UI", "Microsoft YaHei", 微软雅黑, Tahoma, Arial, sans-serif;
            background-color: #f9fafb;
        }
        
        /* 确保toast消息始终显示在最上层 */
        .toast-container {
            z-index: 9999 !important;
        }
        
        /* 自定义滚动条样式 */
        ::-webkit-scrollbar {
            width: 8px;
            height: 8px;
        }
        
        ::-webkit-scrollbar-track {
            background: #f1f1f1;
            border-radius: 4px;
        }
        
        ::-webkit-scrollbar-thumb {
            background: #c1c1c1;
            border-radius: 4px;
        }
        
        ::-webkit-scrollbar-thumb:hover {
            background: #a8a8a8;
        }

        /* 统一表格行高 */
        #materialsList tr td {
            height: 64px;
        }
        
        /* 文件名工具提示样式 */
        .filename-tooltip {
            position: fixed;
            z-index: 1000;
            max-width: 400px;
            background-color: rgba(0, 0, 0, 0.8);
            color: white;
            padding: 6px 10px;
            border-radius: 4px;
            font-size: 12px;
            line-height: 1.4;
            word-break: break-all;
            pointer-events: none;
            opacity: 0;
            transition: opacity 0.2s;
            backdrop-filter: blur(4px);
        }

        /* 页面根样式 */
        :root {
            --sidebar-width: 250px;
            --sidebar-collapsed-width: 70px;
            --transition-speed: 0.3s;
        }

        .sidebar {
            width: var(--sidebar-width);
            transition: all var(--transition-speed) cubic-bezier(0.4, 0, 0.2, 1);
            box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.05);
            z-index: 30;
        }

        .sidebar.collapsed {
            width: var(--sidebar-collapsed-width);
        }

        .sidebar-item span {
            transition: opacity var(--transition-speed), visibility var(--transition-speed);
            white-space: nowrap;
            display: inline-block;
        }

        .sidebar.collapsed .sidebar-item span {
            opacity: 0;
            visibility: hidden;
            width: 0;
            display: none;
        }

        .main-content {
            transition: all var(--transition-speed) cubic-bezier(0.4, 0, 0.2, 1);
            margin-left: var(--sidebar-width);
            width: calc(100% - var(--sidebar-width));
        }

        .main-content.expanded {
            margin-left: var(--sidebar-collapsed-width);
            width: calc(100% - var(--sidebar-collapsed-width));
        }

        #toggleSidebar {
            transition: all 0.2s ease;
            border-radius: 0.375rem;
            width: 38px;
            height: 38px;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        #toggleSidebar:hover {
            background-color: rgba(59, 130, 246, 0.1);
            color: #3b82f6;
            transform: scale(1.05);
        }

        #toggleSidebar:active {
            transform: scale(0.95);
        }

        #toggleSidebar i {
            transition: transform 0.3s ease;
        }

        .sidebar.collapsed + .main-content #toggleSidebar i {
            transform: rotate(180deg);
        }

        .menu-item {
            border-radius: 0.375rem;
            transition: all 0.2s;
        }

        .menu-item:hover {
            background-color: rgba(37, 99, 235, 0.1);
        }

        .menu-item.active {
            background-color: rgba(37, 99, 235, 0.15);
        }

        .menu-item.active i {
            color: #2563eb;
        }

        .notification-badge {
            position: absolute;
            top: -2px;
            right: -2px;
            min-width: 18px;
            height: 18px;
            padding: 0 5px;
            border-radius: 9px;
            background-color: #ef4444;
            color: white;
            font-size: 0.7rem;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .stat-card {
            transition: all 0.3s ease;
        }

        .stat-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05);
        }

        /* 美化用户菜单 */
        .user-profile {
            display: flex;
            align-items: center;
            background-color: rgba(255, 255, 255, 0.8);
            backdrop-filter: blur(10px);
            border-radius: 9999px;
            padding: 0.25rem 0.5rem;
            border: 1px solid rgba(209, 213, 219, 0.4);
            transition: all 0.3s ease;
        }
        
        .user-profile:hover {
            background-color: rgba(255, 255, 255, 0.95);
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
        }
        
        .user-avatar {
            width: 36px;
            height: 36px;
            border-radius: 50%;
            background-color: #60a5fa;
            color: white;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: bold;
            margin-right: 8px;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        }
        
        /* 动画效果 */
        @keyframes fadeIn {
            0% { opacity: 0; transform: translateY(10px); }
            100% { opacity: 1; transform: translateY(0); }
        }
        
        .animate-fade-in {
            animation: fadeIn 0.3s ease-out forwards;
        }
        
        /* 表格美化 */
        table.materials-table {
            border-collapse: separate;
            border-spacing: 0;
            width: 100%;
            border-radius: 0.5rem;
            overflow: hidden;
        }
        
        table.materials-table th {
            background-color: rgba(243, 244, 246, 0.8);
            font-weight: 600;
            padding: 0.75rem 1rem;
            text-transform: uppercase;
            font-size: 0.75rem;
            letter-spacing: 0.05em;
            text-align: left;
            color: #4b5563;
            border-bottom: 1px solid #e5e7eb;
        }
        
        table.materials-table td {
            padding: 1rem;
            border-bottom: 1px solid #e5e7eb;
            transition: background-color 0.2s;
        }
        
        table.materials-table tr:hover td {
            background-color: rgba(59, 130, 246, 0.05);
        }

        .sidebar.collapsed .icon-container {
            margin: 0 auto;
            display: flex;
            justify-content: center;
            width: 100%;
        }

        .sidebar .menu-item {
            border-radius: 0.5rem;
            transition: all 0.2s ease;
            position: relative;
            overflow: hidden;
        }

        .sidebar.collapsed .menu-item {
            padding-left: 0;
            padding-right: 0;
            display: flex;
            justify-content: center;
        }

        .sidebar.collapsed #systemToolsIcon {
            display: none;
        }

        .icon-container {
            transition: all var(--transition-speed) ease;
            display: flex;
            align-items: center;
            justify-content: center;
            width: 1.5rem;
        }

        .sidebar.collapsed .icon-container {
            width: 100%;
            font-size: 1.1em;
        }

        .menu-item:hover {
            background-color: rgba(37, 99, 235, 0.1);
        }

        /* 系统工具菜单样式 */
        .menu-container {
            position: relative;
        }

        .menu-container .submenu {
            display: none;
            position: absolute;
            left: 100%;
            top: 0;
            min-width: 200px;
            background: white;
            border-radius: 0.5rem;
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
            z-index: 50;
        }

        .menu-container .submenu.show {
            display: block;
        }

        .menu-container .submenu a {
            display: block;
            padding: 0.5rem 1rem;
            color: #374151;
            transition: all 0.2s;
            text-decoration: none;
        }

        .menu-container .submenu a:hover {
            background-color: #EBF5FF;
            color: #2563EB;
        }

        /* 确保子菜单在侧边栏折叠时也能正确显示 */
        .sidebar.collapsed .menu-container .submenu {
            left: 100%;
            top: 0;
        }

        .visually-hidden {
          opacity: 0;
          position: absolute;
          left: -9999px;
          width: 1px;
          height: 1px;
          pointer-events: none;
        }
    </style>
</head>
<body class="bg-gray-100 min-h-screen">
<!-- 顶部导航栏 -->
<nav class="bg-white shadow-md fixed w-full z-10">
    <div class="container mx-auto flex items-center justify-between p-3">
        <div class="flex items-center space-x-4">
            <button id="toggleSidebar" class="p-1 rounded-md text-gray-500 hover:bg-gray-100 transition duration-200">
                <i class="fas fa-bars text-lg"></i>
            </button>
            <h1 class="text-xl font-bold text-gray-800">数智作业管理系统</h1>
        </div>
        <div class="flex items-center space-x-3">
            <div class="user-profile" id="userProfileContainer">
                <div class="user-avatar">
                    <i class="fas fa-user"></i>
                </div>
                <div class="hidden md:block">
                    <p id="userFullName" class="text-sm font-medium text-gray-700">用户姓名</p>
                    <p id="userRole" class="text-xs text-gray-500">用户角色</p>
                </div>
                <button id="userMenuBtn" class="ml-2 text-gray-400 hover:text-gray-600 focus:outline-none transition duration-200">
                    <i class="fas fa-chevron-down"></i>
                </button>
                <div id="userDropdown" class="absolute right-4 mt-12 w-48 bg-white rounded-md shadow-lg py-1 z-20 hidden animate-fade-in">
                    <a href="#" id="updateNameBtn" class="block px-4 py-2 text-sm text-gray-700 hover:bg-blue-50 transition duration-200">
                        <i class="fas fa-edit mr-2"></i>修改姓名
                    </a>
                    <a href="#" id="userProfileBtn" class="block px-4 py-2 text-sm text-gray-700 hover:bg-blue-50 transition duration-200">
                        <i class="fas fa-user mr-2"></i>个人资料
                    </a>
                    <div class="border-t border-gray-100 my-1"></div>
                    <a id="logoutBtn" href="#" class="block px-4 py-2 text-sm text-red-600 hover:bg-red-50 transition duration-200">
                        <i class="fas fa-sign-out-alt mr-2"></i>退出登录
                    </a>
                </div>
            </div>
        </div>
    </div>
</nav>

<!-- 侧边导航菜单 -->
<aside id="sidebar" class="sidebar bg-white shadow-md fixed h-full top-0 left-0 pt-16 z-0 overflow-x-hidden">
    <div class="py-4 px-4">
        <div class="mt-2 space-y-2">
            <a href="#" id="materialsBtn" class="menu-item active flex items-center px-4 py-3 text-gray-700">
                <div class="icon-container flex items-center justify-center w-6">
                    <i class="fas fa-box-open text-lg"></i>
                </div>
                <span class="ml-3">通用物料</span>
            </a>

            <!-- 系统工具菜单项 -->
            <div class="menu-container">
                <a href="#" id="systemToolsBtn" class="menu-item flex items-center justify-between px-4 py-3 text-gray-700">
                    <div class="flex items-center">
                        <div class="icon-container flex items-center justify-center w-6">
                            <i class="fas fa-tools text-lg"></i>
                        </div>
                        <span class="ml-3">系统工具</span>
                    </div>
                    <i class="fas fa-chevron-down text-sm transition-transform" id="systemToolsIcon"></i>
                </a>
                <div id="systemToolsSubmenu" class="pl-10 mt-1 space-y-1 hidden">
                    <a href="student-export.html" id="exportStudentId" class="submenu-item block px-4 py-2 text-sm text-gray-700 hover:bg-blue-50 rounded-md">
                        <i class="fas fa-file-export mr-2"></i>学号导出工具
                    </a>
                    <a href="document-merge.html" id="documentMergeTool" class="submenu-item block px-4 py-2 text-sm text-gray-700 hover:bg-blue-50 rounded-md">
                        <i class="fas fa-object-group mr-2"></i>文档合并工具
                    </a>
                    <a href="document-process.html" id="documentProcessTool" class="submenu-item block px-4 py-2 text-sm text-gray-700 hover:bg-blue-50 rounded-md">
                        <i class="fas fa-file-word mr-2"></i>文档处理工具(可AI处理版式）
                    </a>
                    <a href="taskStatistics.html" id="taskStatisticsTool" class="submenu-item block px-4 py-2 text-sm text-gray-700 hover:bg-blue-50 rounded-md">
                        <i class="fas fa-chart-line mr-2"></i>任务统计工具
                    </a>
                </div>
            </div>
        </div>
    </div>
</aside>

<!-- 主要内容区域 -->
<main id="mainContent" class="main-content pt-16 px-4 pb-8">
    <!-- 仪表盘/欢迎内容 -->
    <div id="dashboardContent" class="animate-fade-in">
        <!-- 欢迎横幅 - 减小了padding(p-6改为p-4) -->
        <div class="bg-gradient-to-r from-blue-600 to-indigo-700 rounded-xl shadow-lg mb-4 overflow-hidden">
            <div class="p-4 md:p-6">
                <div class="flex flex-col md:flex-row items-center justify-between">
                    <div class="mb-2 md:mb-0">
                        <h1 class="text-2xl md:text-3xl font-bold text-white mb-2 tracking-wide">欢迎使用数智作业管理系统</h1>
                        <p class="text-blue-100 text-base max-w-2xl leading-relaxed">提高日常工作管理效率，优化内部管理，资源共享平台</p>
                    </div>
                    <div class="hidden md:block">
                    </div>
                </div>
            </div>
            <div class="bg-white bg-opacity-10 px-4 md:px-6 py-2 backdrop-blur-sm">
                <p class="text-white text-sm"><i class="fas fa-info-circle mr-2"></i>系统将不定期更新，增加更多便捷功能。如有建议或问题请联系管理员。</p>
            </div>
        </div>

        <!-- 功能卡片 - 减小了下方margin(mb-6改为mb-4) -->
        <div class="grid grid-cols-1 md:grid-cols-3 gap-4 mb-4">
                <!-- 通用物料卡片 -->
    <div class="bg-white rounded-xl shadow-sm overflow-hidden hover:shadow-md transition-shadow duration-300 border border-gray-100">
        <div class="bg-blue-50 p-4 text-center">
            <div class="flex justify-center items-center h-12 mb-2">
                <i class="fas fa-box-open text-blue-600 text-2xl"></i>
            </div>
            <h2 class="text-lg font-bold text-gray-800 mb-1">通用物料管理</h2>
            <p class="text-gray-600 text-sm h-10">上传、管理和分享各物料资源文件</p>
        </div>
        <div class="p-4 border-t border-gray-100 flex justify-center items-center min-h-[100px]">
            <a href="javascript:void(0)" onclick="showMaterialContent()" class="inline-flex items-center justify-center bg-blue-50 hover:bg-blue-100 text-blue-600 font-medium px-5 py-3 rounded-lg transition-colors w-3/4 text-base shadow-sm hover:shadow">
                <span>进入物料管理</span>
                <i class="fas fa-chevron-right ml-2"></i>
            </a>
        </div>
    </div>

                <!-- 快速入口卡片 -->
    <div class="bg-white rounded-xl shadow-sm overflow-hidden hover:shadow-md transition-shadow duration-300 border border-gray-100">
        <div class="bg-purple-50 p-4 text-center">
            <div class="flex justify-center items-center h-12 mb-2">
                <i class="fas fa-bolt text-purple-600 text-2xl"></i>
            </div>
            <h2 class="text-lg font-bold text-gray-800 mb-1">快速操作</h2>
            <p class="text-gray-600 text-sm h-10">常用功能的便捷入口</p>
        </div>
        <div class="p-4 border-t border-gray-100 flex justify-center items-center min-h-[100px]">
            <div class="grid grid-cols-3 gap-2 w-full">
                <a href="document-process.html" class="flex flex-col items-center justify-center p-2 bg-purple-50 rounded-lg">
                    <i class="fas fa-file-word text-purple-600 text-sm mb-1"></i>
                    <p class="text-xs text-gray-500">文档处理</p>
                    <p class="text-base font-bold text-gray-800">点击跳转</p>
                </a>
                <a href="document-merge.html" class="flex flex-col items-center justify-center p-2 bg-blue-50 rounded-lg">
                    <i class="fas fa-object-group text-blue-600 text-sm mb-1"></i>
                    <p class="text-xs text-gray-500">文档合并</p>
                    <p class="text-base font-bold text-gray-800">点击跳转</p>
                </a>
                <a href="student-export.html" class="flex flex-col items-center justify-center p-2 bg-green-50 rounded-lg">
                    <i class="fas fa-file-export text-green-600 text-sm mb-1"></i>
                    <p class="text-xs text-gray-500">学号导出</p>
                    <p class="text-base font-bold text-gray-800">点击跳转</p>
                </a>
            </div>
        </div>
    </div>

                <!-- 系统概览卡片 -->
    <div class="bg-white rounded-xl shadow-sm overflow-hidden hover:shadow-md transition-shadow duration-300 border border-gray-100">
        <div class="bg-green-50 p-4 text-center">
            <div class="flex justify-center items-center h-12 mb-2">
                <i class="fas fa-chart-line text-green-600 text-2xl"></i>
            </div>
            <h2 class="text-lg font-bold text-gray-800 mb-1">系统概览</h2>
            <p class="text-gray-600 text-sm h-10">当前系统状态概览</p>
        </div>
        <div class="p-4 border-t border-gray-100 flex justify-center items-center min-h-[100px]">
            <div class="grid grid-cols-3 gap-2 w-full">
                <div class="flex flex-col items-center p-2 bg-blue-50 rounded-lg">
                    <i class="fas fa-file text-blue-600 text-sm mb-1"></i>
                    <p class="text-xs text-gray-500">物料数</p>
                    <p class="text-base font-bold text-gray-800" id="totalFilesCount">--</p>
                </div>
                <div class="flex flex-col items-center p-2 bg-purple-50 rounded-lg">
                    <i class="fas fa-users text-purple-600 text-sm mb-1"></i>
                    <p class="text-xs text-gray-500">活跃用户</p>
                    <p class="text-base font-bold text-gray-800" id="activeUsers">--</p>
                </div>
                <div class="flex flex-col items-center p-2 bg-green-50 rounded-lg">
                    <i class="fas fa-bullhorn text-green-600 text-sm mb-1"></i>
                    <p class="text-xs text-gray-500">公告数</p>
                    <p class="text-base font-bold text-gray-800" id="totalNotices">--</p>
                </div>
            </div>
        </div>
    </div>
        </div>

        <!-- 最近更新和公告 - 减小了下方margin(mb-8改为mb-4) -->
        <div class="grid grid-cols-1 gap-4 mb-4">
            <!-- 公告栏 -->
            <div class="bg-white rounded-xl shadow-sm overflow-hidden">
                <div class="p-4 border-b border-gray-100">
                    <div class="flex items-center justify-between">
                        <h2 class="text-xl font-bold text-gray-800">系统公告</h2>
                        <div class="flex space-x-2">
                            <a href="#" id="viewAllNoticesBtn" class="text-blue-600 hover:text-blue-700 text-sm font-medium">查看全部</a>
                            <!-- 管理员可见的添加公告按钮 -->
                            <button id="addNoticeBtn" class="hidden text-green-600 hover:text-green-700 text-sm font-medium ml-4">
                                <i class="fas fa-plus-circle mr-1"></i>添加公告
                            </button>
                        </div>
                    </div>
                </div>
                <div id="noticesList" class="p-4 space-y-3">
                    <!-- 加载状态 -->
                    <div id="noticesLoading" class="py-8 flex justify-center">
                        <div class="flex flex-col items-center">
                            <div class="w-10 h-10 bg-blue-100 rounded-full flex items-center justify-center mb-3">
                                <i class="fas fa-spinner fa-spin text-blue-500"></i>
                            </div>
                            <p class="text-gray-500">正在加载公告...</p>
                        </div>
                    </div>
                    
                    <!-- 无公告状态 -->
                    <div id="noNotices" class="hidden py-8 flex flex-col items-center">
                        <div class="w-16 h-16 bg-gray-100 rounded-full flex items-center justify-center mb-3">
                            <i class="fas fa-bullhorn text-gray-400 text-xl"></i>
                        </div>
                        <p class="text-gray-500 mb-2">暂无系统公告</p>
                        <p class="text-sm text-gray-400">管理员发布的公告将显示在这里</p>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 通用物料内容 -->
    <div id="materialsContent" class="animate-fade-in hidden">
        <!-- 增加上边距，使头部向下移动 -->
        <div class="pt-6 pb-4">
            <!-- 添加标题卡片，使布局更美观 -->
            <div class="bg-white p-5 rounded-xl shadow-sm border border-gray-100 mb-5">
                <div class="flex flex-col md:flex-row md:items-center md:justify-between gap-4">
                    <div class="flex items-center">
                        <button id="backToDashboardBtn" class="mr-4 p-2 bg-blue-50 hover:bg-blue-100 text-blue-600 rounded-lg transition-colors flex items-center shadow-sm">
                            <i class="fas fa-arrow-left"></i>
                            <span class="ml-1 font-medium">返回首页</span>
                        </button>
                        <div>
                            <h2 class="text-2xl font-bold text-gray-800">通用物料管理</h2>
                            <p class="text-gray-500 mt-1 text-sm">管理和共享物料资源文件</p>
                        </div>
                    </div>
                    <div class="flex flex-col md:flex-row gap-3" id="materialsSearchUpload">
                        <div class="relative">
                            <span class="absolute inset-y-0 left-0 flex items-center pl-3">
                                <i class="fas fa-search text-gray-400"></i>
                            </span>
                            <input type="text" id="materialSearch" placeholder="搜索物料..." class="pl-10 pr-10 py-2.5 bg-white border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition duration-200 shadow-sm w-full md:w-64">
                            <button id="clearMaterialSearch" class="absolute inset-y-0 right-0 flex items-center pr-3 text-gray-400 hover:text-gray-600 cursor-pointer hidden">
                                <i class="fas fa-times-circle"></i>
                            </button>
                        </div>
                        <!-- 如果是管理员才显示上传按钮 -->
                        <button id="uploadMaterialBtn" class="px-4 py-2.5 bg-blue-600 text-white rounded-lg hover:bg-blue-700 flex items-center justify-center shadow-sm hover:shadow transition duration-200 font-medium">
                            <i class="fas fa-upload mr-2"></i> 上传物料
                        </button>
                    </div>
                </div>
            </div>
        </div>

        <!-- 物料列表 -->
        <div class="bg-white rounded-xl shadow-sm overflow-hidden border border-gray-100">
            <div class="flex items-center justify-between px-6 py-4 border-b border-gray-100">
                <h3 class="font-semibold text-gray-700">物料文件列表</h3>
                <div class="text-xs text-gray-500">
                    <span id="totalMaterialsCount">--</span> 个文件
                </div>
            </div>
            <div class="overflow-x-auto">
                <table class="min-w-full divide-y divide-gray-200 materials-table">
                    <thead>
                    <tr>
                        <th class="px-6 py-3.5 bg-gray-50 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">文件名</th>
                        <th class="px-6 py-3.5 bg-gray-50 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">描述</th>
                        <th class="px-6 py-3.5 bg-gray-50 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">文件类型</th>
                        <th class="px-6 py-3.5 bg-gray-50 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">大小</th>
                        <th class="px-6 py-3.5 bg-gray-50 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">上传时间</th>
                        <th class="px-6 py-3.5 bg-gray-50 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">上传者</th>
                        <th class="px-6 py-3.5 bg-gray-50 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">操作</th>
                    </tr>
                    </thead>
                    <tbody id="materialsList" class="bg-white divide-y divide-gray-200">
                    <!-- 物料列表项将通过JavaScript动态添加 -->
                    <tr class="animate-pulse bg-white hover:bg-blue-50 transition-colors">
                        <td colspan="7" class="px-6 py-8 text-center text-gray-500">
                            <div class="flex flex-col items-center">
                                <div class="w-10 h-10 bg-blue-100 rounded-full flex items-center justify-center mb-3">
                                    <i class="fas fa-spinner fa-spin text-blue-500"></i>
                                </div>
                                <p>正在加载物料数据...</p>
                            </div>
                        </td>
                    </tr>
                    </tbody>
                </table>
            </div>
            <!-- 空状态显示 -->
            <div id="emptyState" class="hidden py-16 flex flex-col items-center justify-center">
                <div class="bg-blue-50 w-24 h-24 rounded-full flex items-center justify-center mb-6">
                    <i class="fas fa-box-open text-blue-400 text-4xl"></i>
                </div>
                <h3 class="text-xl font-medium text-gray-700 mb-2">暂无物料文件</h3>
                <p class="text-gray-500 mb-6 text-center max-w-md">上传文件以便在这里查看和下载。您可以上传任何格式的文件，包括图片、文档、视频等。</p>
                <button onclick="document.getElementById('uploadMaterialBtn').click()" class="flex items-center px-5 py-2.5 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition duration-200 shadow-sm font-medium">
                    <i class="fas fa-upload mr-2"></i> 立即上传
                </button>
            </div>
            
            <!-- 分页控件（可选，如果有大量物料可添加） -->
            <div id="materialsPagination" class="px-6 py-3 flex items-center justify-between border-t border-gray-200 bg-gray-50 hidden">
                <div class="flex-1 flex justify-between sm:hidden">
                    <a href="#" class="relative inline-flex items-center px-4 py-2 border border-gray-300 text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50">上一页</a>
                    <a href="#" class="ml-3 relative inline-flex items-center px-4 py-2 border border-gray-300 text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50">下一页</a>
                </div>
                <div class="hidden sm:flex-1 sm:flex sm:items-center sm:justify-between">
                    <div>
                        <p class="text-sm text-gray-700">
                            显示第 <span class="font-medium">1</span> 至 <span class="font-medium">10</span> 项，共 <span class="font-medium">20</span> 项
                        </p>
                    </div>
                    <div>
                        <nav class="relative z-0 inline-flex rounded-md shadow-sm -space-x-px" aria-label="Pagination">
                            <a href="#" class="relative inline-flex items-center px-2 py-2 rounded-l-md border border-gray-300 bg-white text-sm font-medium text-gray-500 hover:bg-gray-50">
                                <span class="sr-only">上一页</span>
                                <i class="fas fa-chevron-left"></i>
                            </a>
                            <a href="#" aria-current="page" class="z-10 bg-blue-50 border-blue-500 text-blue-600 relative inline-flex items-center px-4 py-2 border text-sm font-medium">1</a>
                            <a href="#" class="bg-white border-gray-300 text-gray-500 hover:bg-gray-50 relative inline-flex items-center px-4 py-2 border text-sm font-medium">2</a>
                            <a href="#" class="relative inline-flex items-center px-2 py-2 rounded-r-md border border-gray-300 bg-white text-sm font-medium text-gray-500 hover:bg-gray-50">
                                <span class="sr-only">下一页</span>
                                <i class="fas fa-chevron-right"></i>
                            </a>
                        </nav>
                    </div>
                </div>
            </div>
        </div>
    </div>
</main>

<!-- 修改姓名弹窗 -->
<div id="updateNameModal" class="fixed inset-0 flex items-center justify-center z-50 hidden">
    <div class="absolute inset-0 bg-black bg-opacity-60 backdrop-blur-sm"></div>
    <div class="bg-white rounded-xl p-8 max-w-sm mx-4 relative z-10 animate-fade-in shadow-xl">
        <h3 class="text-xl font-bold mb-5 text-gray-800 flex items-center">
            <i class="fas fa-user-edit text-blue-500 mr-3"></i>修改姓名
        </h3>
        <form id="updateNameForm">
            <div class="mb-5">
                <label for="newFullName" class="block text-gray-700 font-medium mb-2">新姓名</label>
                <div class="relative">
                    <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                        <i class="fas fa-user text-gray-400"></i>
                    </div>
                    <input type="text" id="newFullName" name="newFullName"
                          class="border border-gray-300 p-3 pl-10 w-full rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent transition duration-200"
                          placeholder="请输入您的真实姓名" required>
                </div>
            </div>
            <div class="flex justify-end space-x-3">
                <button type="button" id="cancelUpdateName"
                        class="py-2 px-4 bg-gray-200 text-gray-800 rounded-lg hover:bg-gray-300 transition duration-200 focus:outline-none focus:ring-2 focus:ring-gray-300">
                    取消
                </button>
                <button type="submit"
                        class="py-2 px-4 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition duration-200 focus:outline-none focus:ring-2 focus:ring-blue-500 shadow-sm">
                    保存
                </button>
            </div>
        </form>
    </div>
</div>

<!-- 上传物料弹窗 -->
<div id="uploadMaterialModal" class="fixed inset-0 flex items-center justify-center z-50 hidden">
    <div class="absolute inset-0 bg-black bg-opacity-60 backdrop-blur-sm"></div>
    <div class="bg-white rounded-xl p-8 max-w-md w-full mx-4 relative z-10 animate-fade-in shadow-2xl">
        <h3 class="text-xl font-bold mb-5 text-gray-800 flex items-center">
            <i class="fas fa-cloud-upload-alt text-blue-500 mr-3"></i>上传物料文件
        </h3>
        <form id="uploadMaterialForm">
            <div class="mb-5">
                <label for="materialFile" class="block text-gray-700 font-medium mb-2">选择文件</label>
                <div class="border-2 border-dashed border-gray-300 rounded-xl p-8 text-center cursor-pointer hover:bg-gray-50 transition duration-300 file-drop-zone" id="fileDropZone">
                    <input type="file" id="materialFile" name="file" class="visually-hidden" required>
                    <i class="fas fa-cloud-upload-alt text-4xl text-blue-500 mb-3"></i>
                    <p class="text-gray-700 font-medium">点击或拖拽文件至此上传</p>
                    <p class="text-xs text-gray-500 mt-2">支持各种文件格式，最大300MB</p>
                </div>
                <div id="selectedFile" class="mt-3 flex items-center bg-blue-50 p-3 rounded-lg border border-blue-100 hidden">
                    <i class="fas fa-file text-blue-500 mr-3"></i>
                    <span id="selectedFileName" class="text-sm text-gray-700 truncate flex-1"></span>
                    <button type="button" id="removeSelectedFile" class="text-red-500 hover:text-red-700 transition duration-200">
                        <i class="fas fa-times-circle"></i>
                    </button>
                </div>
            </div>
            <div class="mb-5">
                <label for="materialDescription" class="block text-gray-700 font-medium mb-2">文件描述</label>
                <textarea id="materialDescription" name="description" rows="3"
                          class="border border-gray-300 p-3 w-full rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent transition duration-200 resize-none"
                          placeholder="请输入文件描述（可选）"></textarea>
            </div>
            <div class="flex justify-end space-x-3">
                <button type="button" id="cancelUploadMaterial"
                        class="py-2 px-4 bg-gray-200 text-gray-800 rounded-lg hover:bg-gray-300 transition duration-200 focus:outline-none focus:ring-2 focus:ring-gray-300">
                    取消
                </button>
                <button type="submit" id="submitUploadMaterial"
                        class="py-2 px-4 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition duration-200 disabled:bg-blue-300 disabled:cursor-not-allowed focus:outline-none focus:ring-2 focus:ring-blue-500 shadow-sm disabled:shadow-none">
                    上传
                </button>
            </div>
        </form>
    </div>
</div>

<!-- 自定义消息提示弹窗 -->
<div id="messageModal" class="fixed inset-0 flex items-center justify-center z-50 hidden">
    <div class="absolute inset-0 bg-black bg-opacity-60 backdrop-blur-sm"></div>
    <div class="bg-white rounded-xl p-6 max-w-sm w-full mx-4 relative z-10 animate-fade-in shadow-xl">
        <div class="flex items-center mb-4">
            <div id="messageIcon" class="flex-shrink-0 w-12 h-12 flex items-center justify-center rounded-full mr-4">
                <i class="fas fa-exclamation-circle text-2xl"></i>
            </div>
            <h3 id="messageTitle" class="text-lg font-bold text-gray-800">提示</h3>
        </div>
        <p id="messageContent" class="text-gray-700 mb-6">提示内容</p>
        <div class="flex justify-end">
            <button id="messageCloseBtn"
                    class="py-2 px-6 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition duration-200 shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500">
                确定
            </button>
        </div>
    </div>
</div>

<!-- 增强版认证状态弹窗 -->
<div id="authStatusModal" class="fixed inset-0 flex items-center justify-center z-50 hidden">
    <div class="absolute inset-0 bg-black bg-opacity-70 backdrop-blur-sm"></div>
    <div class="bg-white rounded-xl shadow-2xl p-8 max-w-md w-full mx-4 relative z-10 transform transition-all duration-300 scale-100 opacity-100">
        <div class="text-center mb-6">
            <div id="authStatusIcon" class="inline-flex items-center justify-center w-20 h-20 rounded-full mx-auto mb-4"></div>
            <h3 id="authStatusTitle" class="text-2xl font-bold text-gray-800 mb-1">登录状态</h3>
            <p id="authStatusContent" class="text-gray-600">状态信息</p>
        </div>
        <div class="pt-2 border-t border-gray-200">
            <div class="flex justify-center mt-4">
                <button id="authStatusLoginBtn" class="flex items-center justify-center px-6 py-3 bg-blue-600 text-white font-medium rounded-lg hover:bg-blue-700 transition duration-200 shadow-md hover:shadow-lg w-full focus:outline-none focus:ring-2 focus:ring-blue-500">
                    <i class="fas fa-sign-in-alt mr-2"></i>
                    重新登录
                </button>
            </div>
            <p class="text-center text-gray-500 text-sm mt-3" id="authRedirectTimer">5秒后自动跳转至登录页面...</p>
        </div>
    </div>
</div>

<!-- 个人资料弹窗 -->
<div id="userProfileModal" class="fixed inset-0 flex items-center justify-center z-50 hidden">
    <div class="absolute inset-0 bg-black bg-opacity-60 backdrop-blur-sm"></div>
    <div class="bg-white rounded-xl p-8 max-w-md w-full mx-4 relative z-10 animate-fade-in shadow-xl">
        <h3 class="text-xl font-bold mb-5 text-gray-800 flex items-center">
            <i class="fas fa-user-circle text-blue-500 mr-3"></i>个人资料
        </h3>
        <div class="bg-blue-50 p-6 rounded-lg mb-6">
            <div class="flex items-center mb-4">
                <div class="w-16 h-16 rounded-full bg-blue-500 text-white flex items-center justify-center text-2xl font-bold mr-4" id="profileAvatar">
                    A
                </div>
                <div>
                    <h4 class="text-lg font-semibold text-gray-800" id="profileName">用户姓名</h4>
                    <p class="text-sm text-gray-600" id="profileRole">用户角色</p>
                </div>
            </div>
            <div class="grid grid-cols-1 gap-4 text-sm">
                <div class="flex items-center border-b border-blue-100 pb-3">
                    <i class="fas fa-id-badge text-blue-500 w-6"></i>
                    <span class="font-medium text-gray-700 mr-2">账号ID:</span>
                    <span class="text-gray-600" id="profileAccountId">-</span>
                </div>
                <div class="flex items-center border-b border-blue-100 pb-3">
                    <i class="fas fa-calendar-alt text-blue-500 w-6"></i>
                    <span class="font-medium text-gray-700 mr-2">注册时间:</span>
                    <span class="text-gray-600" id="profileRegTime">-</span>
                </div>
                <div class="flex items-center border-b border-blue-100 pb-3">
                    <i class="fas fa-clock text-blue-500 w-6"></i>
                    <span class="font-medium text-gray-700 mr-2">最近登录:</span>
                    <span class="text-gray-600" id="profileLastLogin">-</span>
                </div>
                <div class="flex items-center">
                    <i class="fas fa-shield-alt text-blue-500 w-6"></i>
                    <span class="font-medium text-gray-700 mr-2">登录状态:</span>
                    <span class="px-2 py-1 bg-green-100 text-green-700 rounded-full text-xs font-medium">已登录</span>
                </div>
            </div>
        </div>
        <div class="flex justify-end">
            <button id="closeProfileModal" class="py-2 px-5 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition duration-200 shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500">
                关闭
            </button>
        </div>
    </div>
</div>

<!-- 添加公告弹窗 -->
<div id="addNoticeModal" class="fixed inset-0 flex items-center justify-center z-50 hidden">
    <div class="absolute inset-0 bg-black bg-opacity-60 backdrop-blur-sm"></div>
    <div class="bg-white rounded-xl p-8 max-w-lg w-full mx-4 relative z-10 animate-fade-in shadow-xl">
        <h3 class="text-xl font-bold mb-5 text-gray-800 flex items-center">
            <i class="fas fa-bullhorn text-blue-500 mr-3"></i>
            <span id="noticeModalTitle">发布系统公告</span>
        </h3>
        <form id="noticeForm">
            <input type="hidden" id="noticeId" value="">
            <div class="mb-5">
                <label for="noticeTitle" class="block text-gray-700 font-medium mb-2">公告标题</label>
                <input type="text" id="noticeTitle" name="title" class="border border-gray-300 p-3 w-full rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition duration-200" placeholder="请输入公告标题" required>
            </div>
            <div class="mb-5">
                <label for="noticeContent" class="block text-gray-700 font-medium mb-2">公告内容</label>
                <textarea id="noticeContent" name="content" rows="4" class="border border-gray-300 p-3 w-full rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition duration-200 resize-none" placeholder="请输入公告内容" required></textarea>
            </div>
            <div class="mb-5">
                <label for="noticeType" class="block text-gray-700 font-medium mb-2">公告类型</label>
                <select id="noticeType" name="type" class="border border-gray-300 p-3 w-full rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition duration-200">
                    <option value="normal">普通公告</option>
                    <option value="important">重要公告</option>
                    <option value="warning">警告公告</option>
                    <option value="info">信息公告</option>
                </select>
            </div>
            <div class="flex justify-end space-x-3">
                <button type="button" id="cancelNoticeBtn" class="py-2 px-4 bg-gray-200 text-gray-800 rounded-lg hover:bg-gray-300 transition duration-200 focus:outline-none focus:ring-2 focus:ring-gray-300">
                    取消
                </button>
                <button type="submit" id="submitNoticeBtn" class="py-2 px-4 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition duration-200 focus:outline-none focus:ring-2 focus:ring-blue-500 shadow-sm">
                    发布公告
                </button>
            </div>
        </form>
    </div>
</div>

<!-- 查看公告详情弹窗 -->
<div id="viewNoticeModal" class="fixed inset-0 flex items-center justify-center z-60 hidden">
    <div class="absolute inset-0 bg-black bg-opacity-60 backdrop-blur-sm"></div>
    <div class="bg-white rounded-xl p-8 max-w-lg w-full mx-4 relative z-10 animate-fade-in shadow-xl">
        <div class="flex justify-between items-start mb-5">
            <div class="flex items-center">
                <i class="fas fa-bullhorn text-blue-500 mr-3"></i>
                <span id="viewNoticeTitle" class="text-xl font-bold text-gray-800">公告详情</span>
                <span id="viewNoticeType" class="ml-3 text-xs px-2 py-1 rounded-full"></span>
            </div>
            <div class="flex items-center space-x-2">
                <span id="readStatus" class="hidden text-xs px-2 py-1 bg-green-100 text-green-700 rounded-full">已读</span>
                <div id="noticeAdminControls" class="flex space-x-2 hidden">
                    <button id="editNoticeBtn" class="text-blue-600 hover:text-blue-700 p-1 rounded-full hover:bg-blue-50">
                        <i class="fas fa-edit"></i>
                    </button>
                    <button id="deleteNoticeBtn" class="text-red-600 hover:text-red-700 p-1 rounded-full hover:bg-red-50">
                        <i class="fas fa-trash-alt"></i>
                    </button>
                </div>
            </div>
        </div>
        <div id="viewNoticeContent" class="mb-5 text-gray-700 border-t border-b border-gray-100 py-4">
            <!-- 公告内容将通过JavaScript填充 -->
        </div>
        <div class="flex justify-between items-center text-sm text-gray-500 mb-4">
            <div id="viewNoticeTime">发布时间：-</div>
            <div id="viewNoticeAuthor">发布者：-</div>
        </div>
        
        <!-- 已读人员列表 -->
        <div class="mb-5">
            <div class="flex justify-between items-center mb-2">
                <h4 class="text-sm font-medium text-gray-700">已读人员</h4>
                <span id="readCount" class="text-xs bg-blue-100 text-blue-700 px-2 py-1 rounded-full">0人已读</span>
            </div>
            <div id="readUsersList" class="max-h-40 overflow-y-auto p-3 bg-gray-50 rounded-lg">
                <div id="readUsersLoading" class="py-3 flex justify-center">
                    <div class="flex items-center">
                        <i class="fas fa-spinner fa-spin text-blue-500 mr-2"></i>
                        <span class="text-sm text-gray-500">加载中...</span>
                    </div>
                </div>
                <div id="noReadUsers" class="hidden py-3 text-center text-sm text-gray-500">
                    <i class="fas fa-info-circle mr-1"></i>暂无人员阅读此公告
                </div>
                <!-- 已读用户列表将通过JavaScript填充 -->
            </div>
        </div>
        
        <!-- 未读人员列表（仅管理员可见） -->
        <div id="unreadUsersSection" class="mb-5 hidden">
            <div class="flex justify-between items-center mb-2">
                <h4 class="text-sm font-medium text-gray-700">未读人员</h4>
                <span id="unreadCount" class="text-xs bg-red-100 text-red-700 px-2 py-1 rounded-full">0人未读</span>
            </div>
            <div id="unreadUsersList" class="max-h-40 overflow-y-auto p-3 bg-gray-50 rounded-lg">
                <div id="unreadUsersLoading" class="py-3 flex justify-center">
                    <div class="flex items-center">
                        <i class="fas fa-spinner fa-spin text-blue-500 mr-2"></i>
                        <span class="text-sm text-gray-500">加载中...</span>
                    </div>
                </div>
                <div id="noUnreadUsers" class="hidden py-3 text-center text-sm text-gray-500">
                    <i class="fas fa-check-circle mr-1 text-green-500"></i>所有人员已阅读此公告
                </div>
                <!-- 未读用户列表将通过JavaScript填充 -->
            </div>
        </div>
        
        <div class="flex justify-between">
            <button id="markAsReadBtn" class="hidden py-2 px-4 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition duration-200 focus:outline-none focus:ring-2 focus:ring-blue-300">
                <i class="fas fa-check mr-1"></i>标记为已读
            </button>
            <button type="button" id="closeViewNoticeBtn" class="py-2 px-4 bg-gray-200 text-gray-800 rounded-lg hover:bg-gray-300 transition duration-200 focus:outline-none focus:ring-2 focus:ring-gray-300">
                关闭
            </button>
        </div>
    </div>
</div>

<!-- 添加一个新的全部公告弹窗 -->
<div id="allNoticesModal" class="fixed inset-0 flex items-center justify-center z-50 hidden">
    <div class="absolute inset-0 bg-black bg-opacity-60 backdrop-blur-sm"></div>
    <div class="bg-white rounded-xl p-8 max-w-4xl w-full mx-4 relative z-10 animate-fade-in shadow-xl" style="max-height: 80vh; overflow-y: auto;">
        <div class="flex justify-between items-center mb-6">
            <h3 class="text-xl font-bold text-gray-800 flex items-center">
                <i class="fas fa-bullhorn text-blue-500 mr-3"></i>
                <span>所有系统公告</span>
            </h3>
            <button id="closeAllNoticesBtn" class="text-gray-500 hover:text-gray-700 p-1 rounded-full hover:bg-gray-100">
                <i class="fas fa-times"></i>
            </button>
        </div>
        
        <div id="allNoticesList" class="space-y-4 mb-6">
            <!-- 加载状态 -->
            <div id="allNoticesLoading" class="py-10 flex justify-center">
                <div class="flex flex-col items-center">
                    <div class="w-10 h-10 bg-blue-100 rounded-full flex items-center justify-center mb-3">
                        <i class="fas fa-spinner fa-spin text-blue-500"></i>
                    </div>
                    <p class="text-gray-500">正在加载公告...</p>
                </div>
            </div>
        </div>
        
        <!-- 分页控件 -->
        <div id="noticesPagination" class="flex items-center justify-center space-x-2 py-2 border-t border-gray-100 mt-4">
            <button id="prevPageBtn" class="px-3 py-1 bg-gray-200 text-gray-700 rounded-lg hover:bg-gray-300 transition-colors disabled:opacity-50 disabled:cursor-not-allowed">
                <i class="fas fa-chevron-left mr-1"></i>上一页
            </button>
            <span id="pageIndicator" class="text-gray-600">第 <span id="currentPage">1</span> / <span id="totalPages">1</span> 页</span>
            <button id="nextPageBtn" class="px-3 py-1 bg-gray-200 text-gray-700 rounded-lg hover:bg-gray-300 transition-colors disabled:opacity-50 disabled:cursor-not-allowed">
                下一页<i class="fas fa-chevron-right ml-1"></i>
            </button>
        </div>
    </div>
</div>

<script>
    // 检查登录状态，如果未登录则重定向到登录页
    if (!sessionStorage.getItem('isLoggedIn') || !sessionStorage.getItem('jwtToken')) {
        console.log('未检测到登录状态或JWT令牌，重定向到登录页面');
        window.location.href = 'login.html';
    }

    // 显示用户信息
    document.addEventListener('DOMContentLoaded', function() {
        const userFullName = document.getElementById('userFullName');
        const userRole = document.getElementById('userRole');
        const userAvatar = document.querySelector('.user-avatar');

        // 从会话存储中获取用户信息
        const fullName = sessionStorage.getItem('userFullName');
        const role = sessionStorage.getItem('userRole');

        // 更新显示
        if (userFullName && fullName) {
            userFullName.textContent = fullName;
            
            // 设置用户头像内容 (显示用户名首字母)
            if (userAvatar) {
                userAvatar.textContent = fullName.charAt(0).toUpperCase();
            }
        }

        if (userRole && role) {
            // 格式化角色显示，例如将ROLE_ADMIN转换为"系统管理员"
            let displayRole = role;
            if (role === 'ROLE_ADMIN') {
                displayRole = '系统管理员';
            } else if (role === 'ROLE_USER') {
                displayRole = '普通用户';
            }
            userRole.textContent = displayRole;
        }

        // 初始化全局已读状态映射
        window.readStatusMap = {};
        window.readNoticeIds = new Set();
        
        // 启动令牌有效性检查
        startTokenValidityCheck();

        // 根据角色控制上传物料按钮的显示
        setupMaterialUIByRole();
        
        // 根据角色控制公告管理功能的显示
        setupNoticeUIByRole();
        
        // 初始化菜单状态
        initMenuState();
        
        // 加载所有物料数据
        loadMaterials();
        
        // 加载公告数据
        loadNotices();
        
        // 初始化上传表单
        initUploadForm();
        
        // 仪表盘功能
        initDashboardFeatures();
    });

    // 初始化菜单状态（变更为显示仪表盘）
    async function initMenuState() {
        // 设置菜单项激活状态（默认不激活任何菜单）
        const materialsBtn = document.getElementById('materialsBtn');
        if (materialsBtn) {
            materialsBtn.classList.remove('active');
        }

        // 确保显示仪表盘内容
        const materialsContent = document.getElementById('materialsContent');
        const dashboardContent = document.getElementById('dashboardContent');
        
        if (materialsContent) materialsContent.classList.add('hidden');
        if (dashboardContent) dashboardContent.classList.remove('hidden');
        
        // 设置初始默认值
        setDefaultStats();
        
        // API不存在，直接使用calculateStatsFromDOM获取统计数据
        calculateStatsFromDOM();
    }

    // 设置默认的统计数据
    function setDefaultStats() {
        document.getElementById('totalFilesCount').textContent = '0';
        document.getElementById('activeUsers').textContent = '2';  // 直接设置为数据库中已知的用户数
        document.getElementById('totalNotices').textContent = '0';
    }
    
    // 从DOM中计算统计数据
    async function calculateStatsFromDOM() {
        // 计算物料数
        try {
            const materials = await Api.getMaterials();
            if (materials && Array.isArray(materials)) {
                document.getElementById('totalFilesCount').textContent = materials.length.toString();
            }
        } catch (error) {
            console.error('无法获取物料数据', error);
        }
        
        // 计算公告数
        try {
            const notices = await Api.getNotices();
            if (notices && Array.isArray(notices)) {
                document.getElementById('totalNotices').textContent = notices.length.toString();
            }
        } catch (error) {
            console.error('无法获取公告数据', error);
        }
        
        // 尝试获取用户数量
        try {
            const userCount = await Api.getUsersCount();
            document.getElementById('activeUsers').textContent = userCount.toString();
        } catch (error) {
            console.error('无法获取用户数量', error);
            // 使用默认值
            document.getElementById('activeUsers').textContent = '2';
        }
    }
    
    // 仪表盘功能初始化
    function initDashboardFeatures() {
        // 快速上传按钮 - 根据管理员权限显示/隐藏
        const uploadQuickBtn = document.getElementById('uploadQuickBtn');
        if (uploadQuickBtn) {
            const isAdmin = sessionStorage.getItem('userRole') === 'ROLE_ADMIN';
            
            if (!isAdmin) {
                // 非管理员隐藏上传按钮
                const parentElement = uploadQuickBtn.parentElement;
                if (parentElement) {
                    parentElement.removeChild(uploadQuickBtn);
                }
            }
        }
    }

    // 获取所有菜单项 (主菜单和子菜单)
    const allMenuItems = document.querySelectorAll('.menu-item, .submenu-item');
    const dashboardContent = document.getElementById('dashboardContent');
    const materialsContent = document.getElementById('materialsContent');

    // 根据用户角色设置物料界面
    function setupMaterialUIByRole() {
        const isAdmin = Api.isAdmin();
        const uploadMaterialBtn = document.getElementById('uploadMaterialBtn');

        if (uploadMaterialBtn) {
            if (!isAdmin) {
                uploadMaterialBtn.classList.add('hidden');
            } else {
                uploadMaterialBtn.classList.remove('hidden');
            }
        }
    }
    
    // 根据用户角色设置公告界面
    function setupNoticeUIByRole() {
        const isAdmin = Api.isAdmin();
        const addNoticeBtn = document.getElementById('addNoticeBtn');
        const noticeAdminControls = document.getElementById('noticeAdminControls');
        
        // 管理员可以添加公告
        if (addNoticeBtn) {
            if (isAdmin) {
                addNoticeBtn.classList.remove('hidden');
            } else {
                addNoticeBtn.classList.add('hidden');
            }
        }
        
        // 管理员可以编辑和删除公告
        if (noticeAdminControls) {
            if (isAdmin) {
                noticeAdminControls.classList.remove('hidden');
            } else {
                noticeAdminControls.classList.add('hidden');
            }
        }
    }

    // 菜单项点击事件
    allMenuItems.forEach(item => {
        // 跳过系统工具父菜单按钮，因为它有单独的监听器
        if (item.id === 'systemToolsBtn') {
            return;
        }

        item.addEventListener('click', (e) => {
            // 如果是普通的 # 链接，阻止默认行为并处理激活
            if (item.getAttribute('href') === '#') {
                e.preventDefault();
                // 移除所有菜单项的激活状态
                allMenuItems.forEach(i => i.classList.remove('active'));
                // 添加激活状态到当前点击项
                item.classList.add('active');

                // 隐藏仪表盘，显示相应内容
                const dashboardContent = document.getElementById('dashboardContent');
                if(dashboardContent) {
                    dashboardContent.classList.add('hidden');
                }

                // 通用物料处理 - 确保物料内容可见
                if (item.id === 'materialsBtn') {
                    if(materialsContent) {
                        materialsContent.classList.remove('hidden');
                        loadMaterials(); // 加载物料数据
                    }
                }
            } else {
                // 对于指向实际页面的链接，只处理激活状态，允许默认的页面跳转
                allMenuItems.forEach(i => i.classList.remove('active'));
                item.classList.add('active');
                // 如果该项属于子菜单，其父菜单项也取消激活
                if (item.classList.contains('submenu-item') && systemToolsBtn) {
                    systemToolsBtn.classList.remove('active');
                }
            }
        });
    });

    // 物料管理相关功能
    const uploadMaterialBtn = document.getElementById('uploadMaterialBtn');
    const uploadMaterialModal = document.getElementById('uploadMaterialModal');
    const uploadMaterialForm = document.getElementById('uploadMaterialForm');
    const cancelUploadMaterial = document.getElementById('cancelUploadMaterial');
    const materialFile = document.getElementById('materialFile');
    const fileDropZone = document.getElementById('fileDropZone');
    const selectedFile = document.getElementById('selectedFile');
    const selectedFileName = document.getElementById('selectedFileName');
    const removeSelectedFile = document.getElementById('removeSelectedFile');
    const submitUploadMaterial = document.getElementById('submitUploadMaterial');
    const materialSearch = document.getElementById('materialSearch');

    // 如果DOM元素存在，则设置事件监听
    if (uploadMaterialBtn) {
        uploadMaterialBtn.addEventListener('click', () => {
            uploadMaterialModal.classList.remove('hidden');
        });
    }

    if (cancelUploadMaterial) {
        cancelUploadMaterial.addEventListener('click', () => {
            uploadMaterialModal.classList.add('hidden');
            resetUploadForm();
        });
    }

    if (removeSelectedFile) {
        removeSelectedFile.addEventListener('click', () => {
            resetUploadForm();
        });
    }

    // 点击蒙层关闭弹窗
    if (uploadMaterialModal) {
        uploadMaterialModal.addEventListener('click', (e) => {
            if (e.target === uploadMaterialModal) {
                uploadMaterialModal.classList.add('hidden');
                resetUploadForm();
            }
        });
    }

    // 文件拖放功能
    if (fileDropZone) {
        fileDropZone.addEventListener('click', () => {
            materialFile.click();
        });

        fileDropZone.addEventListener('dragover', (e) => {
            e.preventDefault();
            fileDropZone.classList.add('bg-blue-50', 'border-blue-300');
        });

        fileDropZone.addEventListener('dragleave', () => {
            fileDropZone.classList.remove('bg-blue-50', 'border-blue-300');
        });

        fileDropZone.addEventListener('drop', (e) => {
            e.preventDefault();
            fileDropZone.classList.remove('bg-blue-50', 'border-blue-300');

            if (e.dataTransfer.files.length) {
                handleFileSelection(e.dataTransfer.files[0]);
                // 同步 input[type=file] 的 files
                const dataTransfer = new DataTransfer();
                dataTransfer.items.add(e.dataTransfer.files[0]);
                materialFile.files = dataTransfer.files;
            }
        });
    }

    // 文件选择
    if (materialFile) {
        materialFile.addEventListener('change', (e) => {
            if (e.target.files.length) {
                handleFileSelection(e.target.files[0]);
            }
        });
    }

    // 处理文件选择
    function handleFileSelection(file) {
        if (file) {
            // 不再进行文件大小验证，仅依赖服务器端验证
            selectedFileName.textContent = file.name;
            selectedFile.classList.remove('hidden');
            fileDropZone.classList.add('border-green-300', 'bg-green-50');
            submitUploadMaterial.disabled = false;
        }
    }

    // 格式化文件大小显示
    function formatFileSize(bytes) {
        if (bytes === 0) return '0 B';
        const k = 1024;
        const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
        const i = Math.floor(Math.log(bytes) / Math.log(k));
        return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
    }

    // 重置上传表单
    function resetUploadForm() {
        uploadMaterialForm.reset();
        selectedFile.classList.add('hidden');
        fileDropZone.classList.remove('border-green-300', 'bg-green-50', 'border-blue-300', 'bg-blue-50');
        submitUploadMaterial.disabled = true;
    }

    // 提交上传表单
    if (uploadMaterialForm) {
        uploadMaterialForm.addEventListener('submit', async (e) => {
            e.preventDefault();

            const formData = new FormData(uploadMaterialForm);
            submitUploadMaterial.disabled = true;
            submitUploadMaterial.innerHTML = '<i class="fas fa-spinner fa-spin mr-2"></i>上传中...';

            try {
                const result = await Api.uploadMaterial(formData);

                if (result && result.success) {
                    uploadMaterialModal.classList.add('hidden');
                    resetUploadForm();
                    showMessage('上传成功', '文件已成功上传', 'success');
                    loadMaterials(); // 重新加载物料列表
                } else {
                    // 显示具体错误信息
                    const errorMessage = result && result.message ? result.message : '未知错误';
                    showMessage('上传失败', errorMessage, 'error');
                }
            } catch (error) {
                console.error('上传文件出错:', error);

                // 尝试从错误对象中获取更详细的错误信息
                let errorMessage = '请稍后重试';

                if (error.response) {
                    try {
                        // 尝试读取响应体的错误消息
                        const errorData = await error.response.json();
                        if (errorData && errorData.message) {
                            errorMessage = errorData.message;
                        }
                    } catch (e) {
                        // 如果不是JSON响应，使用HTTP状态文本
                        errorMessage = error.response.statusText || '服务器错误';
                    }
                } else if (error.message) {
                    errorMessage = error.message;
                }

                showMessage('上传失败', errorMessage, 'error');
            } finally {
                submitUploadMaterial.disabled = false;
                submitUploadMaterial.innerHTML = '上传';
            }
        });
    }

    // 加载物料列表
    async function loadMaterials() {
        const materialsList = document.getElementById('materialsList');
        const emptyState = document.getElementById('emptyState');

        if (!materialsList) return;

        try {
            // 显示加载状态
            materialsList.innerHTML = `
                <tr class="animate-pulse bg-white">
                    <td colspan="7" class="px-6 py-8 text-center text-gray-500">
                        <div class="flex flex-col items-center">
                            <div class="w-10 h-10 bg-blue-100 rounded-full flex items-center justify-center mb-3">
                                <i class="fas fa-spinner fa-spin text-blue-500"></i>
                            </div>
                            <p>正在加载物料数据...</p>
                        </div>
                    </td>
                </tr>`;

            const materials = await Api.getMaterials();

            if (materials && materials.length > 0) {
                // 有数据，渲染列表
                materialsList.innerHTML = '';
                emptyState.classList.add('hidden');
                
                // 更新总文件数显示
                const totalMaterialsCount = document.getElementById('totalMaterialsCount');
                if (totalMaterialsCount) {
                    totalMaterialsCount.textContent = materials.length;
                }

                materials.forEach(material => {
                    const row = document.createElement('tr');
                    row.classList.add('hover:bg-blue-50', 'transition-colors', 'duration-150');

                    // 格式化文件大小
                    let size = material.fileSize;
                    let sizeUnit = 'B';
                    if (size > 1024) { size = (size / 1024); sizeUnit = 'KB'; }
                    if (size > 1024) { size = (size / 1024); sizeUnit = 'MB'; }
                    if (size > 1024) { size = (size / 1024); sizeUnit = 'GB'; }
                    const formattedSize = `${size.toFixed(1)} ${sizeUnit}`;

                    // 格式化日期
                    const uploadDate = new Date(material.uploadTime);
                    const formattedDate = uploadDate.toLocaleString('zh-CN');

                    // 获取文件图标
                    const fileIcon = getFileIcon(material.fileType, material.fileName);

                    // 是否显示删除按钮（只有管理员才显示）
                    const isAdmin = Api.isAdmin();
                    const deleteBtn = isAdmin ? `
                        <button class="delete-material text-red-500 hover:text-red-600 transition duration-200 p-2 rounded-full hover:bg-red-50" data-id="${material.id}" title="删除">
                            <i class="fas fa-trash-alt"></i>
                        </button>` : '';

                    // 操作按钮样式美化
                    row.innerHTML = `
                        <td class="px-6 py-4 whitespace-nowrap">
                            <div class="flex items-center">
                                <div class="flex-shrink-0 text-xl mr-3">${fileIcon}</div>
                                <div class="text-sm font-medium text-gray-900 truncate max-w-xs" title="${material.fileName}">${material.fileName}</div>
                            </div>
                        </td>
                        <td class="px-6 py-4">
                            <div class="text-sm text-gray-700 truncate max-w-xs" title="${material.description || '无描述'}">${material.description || '<span class="text-gray-400 italic">无描述</span>'}</div>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap">
                            <span class="px-2.5 py-1 inline-flex text-xs leading-5 font-medium rounded-full bg-blue-50 text-blue-700">${getFileTypeDisplay(material.fileType)}</span>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap">
                            <div class="text-sm text-gray-700">${formattedSize}</div>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap">
                            <div class="text-sm text-gray-700">${formattedDate}</div>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap">
                            <div class="text-sm text-gray-700">${material.uploadUser}</div>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap text-right text-sm font-medium space-x-1">
                            <button class="preview-material text-blue-600 hover:text-blue-700 transition duration-200 p-2 rounded-full hover:bg-blue-50"
                                    data-id="${material.id}"
                                    data-filename="${material.fileName}"
                                    data-filetype="${material.fileType}"
                                    title="预览">
                                <i class="fas fa-eye"></i>
                            </button>
                            <button class="download-material text-green-600 hover:text-green-700 transition duration-200 p-2 rounded-full hover:bg-green-50"
                                    data-id="${material.id}"
                                    data-filename="${material.fileName}"
                                    title="下载">
                                <i class="fas fa-download"></i>
                            </button>
                            ${deleteBtn}
                        </td>
                    `;

                    materialsList.appendChild(row);
                });

                // 添加下载事件监听
                document.querySelectorAll('.download-material').forEach(btn => {
                    btn.addEventListener('click', async (e) => {
                        const materialId = e.currentTarget.dataset.id;
                        const filename = e.currentTarget.dataset.filename;
                        // 使用新增的下载方法
                        Api.downloadMaterial(materialId, filename);
                    });
                });

                // 添加预览事件监听
                document.querySelectorAll('.preview-material').forEach(btn => {
                    btn.addEventListener('click', async (e) => {
                        const materialId = e.currentTarget.dataset.id;
                        const filename = e.currentTarget.dataset.filename;
                        const fileType = e.currentTarget.dataset.filetype;
                        // 调用预览方法
                        Api.previewMaterial(materialId, filename, fileType);
                    });
                });

                // 添加删除事件监听
                document.querySelectorAll('.delete-material').forEach(btn => {
                    btn.addEventListener('click', async (e) => {
                        const materialId = e.currentTarget.dataset.id;
                        if (confirm('确定要删除此文件吗？此操作不可恢复。')) {
                            try {
                                const result = await Api.deleteMaterial(materialId);
                                if (result && result.success) {
                                    showMessage('删除成功', '文件已成功删除', 'success');
                                    loadMaterials();
                                } else {
                                    showMessage('删除失败', result ? result.message : '未知错误', 'error');
                                }
                            } catch (error) {
                                console.error('删除文件出错:', error);
                                showMessage('删除失败', '请稍后重试', 'error');
                            }
                        }
                    });
                });
            } else {
                // 无数据，显示空状态
                materialsList.innerHTML = '';
                emptyState.classList.remove('hidden');
            }
        } catch (error) {
            console.error('加载物料列表出错:', error);
            materialsList.innerHTML = `
                <tr>
                    <td colspan="7" class="px-6 py-8 text-center text-red-500">
                        <div class="flex flex-col items-center">
                            <div class="w-10 h-10 bg-red-100 rounded-full flex items-center justify-center mb-3">
                                <i class="fas fa-exclamation-circle text-red-500"></i>
                            </div>
                            <p>加载物料数据失败，请刷新页面重试</p>
                        </div>
                    </td>
                </tr>`;
        }
    }

    // 搜索功能
    if (materialSearch) {
        materialSearch.addEventListener('input', (e) => {
            const searchValue = e.target.value.toLowerCase().trim();
            const rows = document.querySelectorAll('#materialsList tr');
            const clearButton = document.getElementById('clearMaterialSearch');
            
            if (searchValue === '') {
                // 如果搜索框为空，显示所有行
                rows.forEach(row => row.classList.remove('hidden'));
                const emptyState = document.getElementById('emptyState');
                if (emptyState && rows.length > 0) {
                    emptyState.classList.add('hidden');
                }
                if (clearButton) clearButton.classList.add('hidden');
                return;
            }
            
            // 显示清除按钮
            if (clearButton) clearButton.classList.remove('hidden');
            
            // 分词处理，支持多个关键词搜索
            const keywords = searchValue.split(/\s+/).filter(k => k.length > 0);
            
            // 搜索处理
            rows.forEach(row => {
                const content = row.textContent.toLowerCase();
                
                // 如果存在多个关键词，要求都匹配
                if (keywords.length > 0) {
                    const allMatch = keywords.every(keyword => content.includes(keyword));
                    if (allMatch) {
                        row.classList.remove('hidden');
                    } else {
                        row.classList.add('hidden');
                    }
                } else {
                    row.classList.remove('hidden');
                }
            });

            // 检查是否有可见行，没有则显示无匹配结果
            const visibleRows = Array.from(rows).filter(row => !row.classList.contains('hidden'));
            const emptyState = document.getElementById('emptyState');

            if (visibleRows.length === 0 && searchValue) {
                if (emptyState) {
                    emptyState.innerHTML = `
                        <div class="bg-gray-50 w-24 h-24 rounded-full flex items-center justify-center mb-6">
                            <i class="fas fa-search text-gray-400 text-4xl"></i>
                        </div>
                        <h3 class="text-xl font-medium text-gray-700 mb-2">没有匹配的结果</h3>
                        <p class="text-gray-500 mb-6 text-center max-w-md">没有找到与"${searchValue}"相匹配的物料文件。请尝试使用其他关键词或更一般性的搜索词。</p>
                        <button id="clearSearchBtn" class="flex items-center px-4 py-2 bg-gray-200 text-gray-800 rounded-lg hover:bg-gray-300 transition duration-200">
                            <i class="fas fa-times mr-2"></i> 清除搜索
                        </button>
                    `;
                    emptyState.classList.remove('hidden');
                    
                    // 添加清除搜索按钮事件
                    document.getElementById('clearSearchBtn')?.addEventListener('click', () => {
                        materialSearch.value = '';
                        materialSearch.dispatchEvent(new Event('input'));
                        materialSearch.focus();
                    });
                }
            } else {
                if (emptyState) {
                    emptyState.classList.add('hidden');
                }
            }
        });
        
        // 清除搜索按钮点击事件
        document.getElementById('clearMaterialSearch')?.addEventListener('click', () => {
            materialSearch.value = '';
            materialSearch.dispatchEvent(new Event('input'));
            materialSearch.focus();
        });
        
        // 添加搜索框快捷键(Esc清空搜索)
        materialSearch.addEventListener('keydown', (e) => {
            if (e.key === 'Escape') {
                materialSearch.value = '';
                materialSearch.dispatchEvent(new Event('input'));
            }
        });
    }

    // 根据文件类型获取图标
    function getFileIcon(fileType, fileName) {
        if (!fileType) {
            fileType = '';
        }

        if (fileType.includes('pdf')) {
            return '<i class="fas fa-file-pdf text-red-500"></i>';
        } else if (fileType.includes('word') || fileName.endsWith('.doc') || fileName.endsWith('.docx')) {
            return '<i class="fas fa-file-word text-blue-500"></i>';
        } else if (fileType.includes('excel') || fileName.endsWith('.xls') || fileName.endsWith('.xlsx')) {
            return '<i class="fas fa-file-excel text-green-500"></i>';
        } else if (fileType.includes('powerpoint') || fileName.endsWith('.ppt') || fileName.endsWith('.pptx')) {
            return '<i class="fas fa-file-powerpoint text-orange-500"></i>';
        } else if (fileType.includes('image')) {
            return '<i class="fas fa-file-image text-purple-500"></i>';
        } else if (fileType.includes('audio')) {
            return '<i class="fas fa-file-audio text-yellow-500"></i>';
        } else if (fileType.includes('video')) {
            return '<i class="fas fa-file-video text-pink-500"></i>';
        } else if (fileType.includes('zip') || fileType.includes('rar') || fileType.includes('archive') ||
            fileName.endsWith('.zip') || fileName.endsWith('.rar') || fileName.endsWith('.7z')) {
            return '<i class="fas fa-file-archive text-amber-500"></i>';
        } else if (fileType.includes('text')) {
            return '<i class="fas fa-file-alt text-gray-500"></i>';
        } else if (fileType.includes('code') || fileName.endsWith('.java') || fileName.endsWith('.js') ||
            fileName.endsWith('.py') || fileName.endsWith('.html') || fileName.endsWith('.css')) {
            return '<i class="fas fa-file-code text-indigo-500"></i>';
        } else {
            return '<i class="fas fa-file text-gray-500"></i>';
        }
    }

    // 格式化文件类型显示
    function getFileTypeDisplay(fileType) {
        if (!fileType) return '未知类型';

        if (fileType.includes('pdf')) {
            return 'PDF文档';
        } else if (fileType.includes('word')) {
            return 'Word文档';
        } else if (fileType.includes('excel') || fileType.includes('spreadsheetml')) {
            return 'Excel表格';
        } else if (fileType.includes('powerpoint')) {
            return 'PowerPoint演示文稿';
        } else if (fileType.includes('image')) {
            return '图片';
        } else if (fileType.includes('audio')) {
            return '音频';
        } else if (fileType.includes('video')) {
            return '视频';
        } else if (fileType.includes('zip') || fileType.includes('rar') || fileType.includes('archive')) {
            return '压缩文件';
        } else if (fileType.includes('text')) {
            return '文本文件';
        } else if (fileType.includes('html')) {
            return 'HTML文件';
        } else if (fileType.includes('javascript')) {
            return 'JavaScript文件';
        } else {
            // 从MIME类型中提取主要部分
            const mainType = fileType.split('/')[0];
            const subType = fileType.split('/')[1];
            if (mainType && subType) {
                return subType.toUpperCase() + '文件';
            }
            return fileType;
        }
    }

    // 初始化用户选项菜单
    const userMenuBtn = document.getElementById('userMenuBtn');
    const userDropdown = document.getElementById('userDropdown');
    const userProfileContainer = document.getElementById('userProfileContainer');

    if (userMenuBtn && userDropdown) {
        userMenuBtn.addEventListener('click', (e) => {
            e.stopPropagation();
            userDropdown.classList.toggle('hidden');
        });

        // 点击用户信息区域也能触发下拉菜单
        if (userProfileContainer) {
            userProfileContainer.addEventListener('click', (e) => {
                // 如果点击的是下拉按钮，不做处理，因为按钮有自己的事件处理
                if (e.target === userMenuBtn || userMenuBtn.contains(e.target)) {
                    return;
                }
                e.stopPropagation();
                userDropdown.classList.toggle('hidden');
            });
        }

        // 点击页面其他地方关闭下拉菜单
        document.addEventListener('click', (e) => {
            if (!userMenuBtn.contains(e.target) && !userDropdown.contains(e.target) && 
                (!userProfileContainer || !userProfileContainer.contains(e.target))) {
                userDropdown.classList.add('hidden');
            }
        });
    }

    // 退出登录按钮
    const logoutBtn = document.getElementById('logoutBtn');
    logoutBtn.addEventListener('click', async (e) => {
        e.preventDefault();

        try {
            // 调用登出API
            const success = await Api.logout();
            if (success) {
                console.log('登出成功');
            } else {
                console.warn('登出API调用失败');
            }
        } catch (error) {
            console.error('登出出错:', error);
        }

        // 不管API调用是否成功，都清除本地存储并重定向
        sessionStorage.removeItem('isLoggedIn');
        sessionStorage.removeItem('jwtToken');
        sessionStorage.removeItem('userFullName');
        sessionStorage.removeItem('userRole');
        localStorage.removeItem('rememberMe');
        window.location.href = 'login.html';
    });

    // 修改姓名功能
    const updateNameBtn = document.getElementById('updateNameBtn');
    const updateNameModal = document.getElementById('updateNameModal');
    const updateNameForm = document.getElementById('updateNameForm');
    const cancelUpdateName = document.getElementById('cancelUpdateName');
    const newFullNameInput = document.getElementById('newFullName');

    // 显示修改姓名弹窗
    updateNameBtn.addEventListener('click', (e) => {
        e.preventDefault();
        e.stopPropagation();

        // 获取当前姓名作为默认值
        const currentName = document.getElementById('userFullName').textContent;
        newFullNameInput.value = currentName;

        // 显示弹窗
        updateNameModal.classList.remove('hidden');
        userDropdown.classList.add('hidden');
    });

    // 取消修改姓名
    cancelUpdateName.addEventListener('click', () => {
        updateNameModal.classList.add('hidden');
    });

    // 点击弹窗外部关闭
    updateNameModal.addEventListener('click', (e) => {
        if (e.target === updateNameModal) {
            updateNameModal.classList.add('hidden');
        }
    });

    // 提交姓名修改
    updateNameForm.addEventListener('submit', async (e) => {
        e.preventDefault();

        const newFullName = newFullNameInput.value.trim();
        if (!newFullName) {
            showMessage('警告', '姓名不能为空', 'warning');
            return;
        }

        try {
            const result = await Api.updateFullName(newFullName);

            if (result && result.success) {
                // 更新显示和会话存储
                document.getElementById('userFullName').textContent = result.fullName;
                sessionStorage.setItem('userFullName', result.fullName);

                // 关闭弹窗
                updateNameModal.classList.add('hidden');

                // 显示成功提示
                showMessage('成功', '姓名更新成功', 'success');

                console.log('姓名更新成功:', result.fullName);
            } else {
                showMessage('更新失败', result ? result.message : '未知错误', 'error');
            }
        } catch (error) {
            console.error('更新姓名出错:', error);
            showMessage('更新失败', '请稍后重试', 'error');
        }
    });

    // 系统工具菜单折叠/展开功能
    const systemToolsBtn = document.getElementById('systemToolsBtn');
    const systemToolsSubmenu = document.getElementById('systemToolsSubmenu');
    const systemToolsIcon = document.getElementById('systemToolsIcon');

    if (systemToolsBtn && systemToolsSubmenu && systemToolsIcon) {
        systemToolsBtn.addEventListener('click', (e) => {
            e.preventDefault();
            e.stopPropagation(); // 防止事件冒泡

            // 切换显示状态
            systemToolsSubmenu.classList.toggle('hidden');
            systemToolsIcon.classList.toggle('rotate-180');

            // 保存菜单状态到 localStorage
            const isExpanded = !systemToolsSubmenu.classList.contains('hidden');
            localStorage.setItem('systemToolsExpanded', isExpanded.toString());
        });
    }

    // 页面加载时恢复菜单状态
    document.addEventListener('DOMContentLoaded', function() {
        const systemToolsExpanded = localStorage.getItem('systemToolsExpanded') === 'true';
        if (systemToolsExpanded) {
            if (systemToolsSubmenu) systemToolsSubmenu.classList.remove('hidden');
            if (systemToolsIcon) systemToolsIcon.classList.add('rotate-180');
        }
    });

    // 侧边栏折叠/展开功能
    const toggleSidebar = document.getElementById('toggleSidebar');
    const sidebar = document.getElementById('sidebar');
    const mainContent = document.getElementById('mainContent');

    // 从本地存储中获取侧边栏状态
    const isSidebarCollapsed = localStorage.getItem('sidebarCollapsed') === 'true';
    
    // 页面加载时应用保存的侧边栏状态
    if (isSidebarCollapsed) {
        sidebar.classList.add('collapsed');
        mainContent.classList.add('expanded');
        if (systemToolsSubmenu) systemToolsSubmenu.classList.add('hidden');
        if (systemToolsIcon) systemToolsIcon.classList.remove('rotate-180');
        
        // 设置折叠按钮图标
        const toggleIcon = toggleSidebar.querySelector('i');
        toggleIcon.classList.remove('fa-bars');
        toggleIcon.classList.add('fa-bars-staggered');
    }

    toggleSidebar.addEventListener('click', () => {
        sidebar.classList.toggle('collapsed');
        mainContent.classList.toggle('expanded');

        // 保存侧边栏状态到本地存储
        localStorage.setItem('sidebarCollapsed', sidebar.classList.contains('collapsed'));

        // 当侧边栏折叠时也需要隐藏子菜单
        if (sidebar.classList.contains('collapsed')) {
            if (systemToolsSubmenu) systemToolsSubmenu.classList.add('hidden');
            if (systemToolsIcon) systemToolsIcon.classList.remove('rotate-180');
        }
        
        // 更新折叠按钮图标
        toggleSidebar.querySelector('i').classList.toggle('fa-bars');
        toggleSidebar.querySelector('i').classList.toggle('fa-bars-staggered');
    });

    // 定期检查token有效性
    function startTokenValidityCheck() {
        // 每15分钟检查一次token有效性，而不是之前的30秒
        setInterval(async () => {
            try {
                const token = sessionStorage.getItem('jwtToken');
                if (!token) {
                    console.warn('没有找到token，无法检查有效性');
                    return;
                }
                
                // 先检查token是否即将过期
                const response = await fetch('/api/check-token-expiry', {
                    method: 'POST',
                    headers: {
                        'Authorization': `Bearer ${token}`
                    }
                });
                
                if (response.ok) {
                    const data = await response.json();
                    // 如果token即将过期，主动刷新
                    if (data.nearExpiry) {
                        console.log('Token即将过期，主动刷新');
                        const refreshResult = await Api.refreshToken();
                        if (refreshResult) {
                            console.log('Token刷新成功');
                        } else {
                            console.warn('Token刷新失败');
                        }
                    }
                } else {
                    // 如果请求失败，可能token已经过期，Api.fetchWithToken会自动处理
                    console.warn('检查token有效期失败，可能已过期');
                }
            } catch (error) {
                console.error('检查token有效性时出错:', error);
            }
        }, 15 * 60 * 1000); // 15分钟
    }

    // 显示自定义消息弹窗
    function showMessage(title, content, type = 'info') {
        const modal = document.getElementById('messageModal');
        const titleEl = document.getElementById('messageTitle');
        const contentEl = document.getElementById('messageContent');
        const iconEl = document.getElementById('messageIcon');
        const closeBtn = document.getElementById('messageCloseBtn');

        titleEl.textContent = title;
        contentEl.textContent = content;

        // 根据消息类型设置图标和颜色
        switch(type) {
            case 'success':
                iconEl.className = 'flex-shrink-0 w-10 h-10 flex items-center justify-center rounded-full mr-4 bg-green-100';
                iconEl.innerHTML = '<i class="fas fa-check-circle text-2xl text-green-600"></i>';
                break;
            case 'warning':
                iconEl.className = 'flex-shrink-0 w-10 h-10 flex items-center justify-center rounded-full mr-4 bg-yellow-100';
                iconEl.innerHTML = '<i class="fas fa-exclamation-triangle text-2xl text-yellow-600"></i>';
                break;
            case 'error':
                iconEl.className = 'flex-shrink-0 w-10 h-10 flex items-center justify-center rounded-full mr-4 bg-red-100';
                iconEl.innerHTML = '<i class="fas fa-times-circle text-2xl text-red-600"></i>';
                break;
            default: // info
                iconEl.className = 'flex-shrink-0 w-10 h-10 flex items-center justify-center rounded-full mr-4 bg-blue-100';
                iconEl.innerHTML = '<i class="fas fa-info-circle text-2xl text-blue-600"></i>';
        }

        // 显示弹窗
        modal.classList.remove('hidden');

        // 点击关闭按钮
        closeBtn.onclick = () => {
            modal.classList.add('hidden');
        };

        // 点击蒙层也关闭
        modal.addEventListener('click', (e) => {
            if (e.target === modal) {
                modal.classList.add('hidden');
            }
        });
    }

    // 显示增强版认证状态弹窗
    function showAuthModal(title, message, errorType = 'session_expired') {
        const modal = document.getElementById('authStatusModal');
        const titleEl = document.getElementById('authStatusTitle');
        const contentEl = document.getElementById('authStatusContent');
        const iconEl = document.getElementById('authStatusIcon');
        const loginBtn = document.getElementById('authStatusLoginBtn');
        const timerEl = document.getElementById('authRedirectTimer');

        // 设置弹窗内容
        titleEl.textContent = title;
        contentEl.textContent = message;

        // 根据错误类型设置不同的图标和样式
        switch(errorType) {
            case 'account_elsewhere':
                iconEl.className = 'inline-flex items-center justify-center w-20 h-20 rounded-full mx-auto mb-4 bg-yellow-100';
                iconEl.innerHTML = '<i class="fas fa-user-lock text-4xl text-yellow-600"></i>';
                break;
            case 'token_expired':
                iconEl.className = 'inline-flex items-center justify-center w-20 h-20 rounded-full mx-auto mb-4 bg-blue-100';
                iconEl.innerHTML = '<i class="fas fa-hourglass-end text-4xl text-blue-600"></i>';
                break;
            case 'token_invalid':
                iconEl.className = 'inline-flex items-center justify-center w-20 h-20 rounded-full mx-auto mb-4 bg-red-100';
                iconEl.innerHTML = '<i class="fas fa-exclamation-triangle text-4xl text-red-600"></i>';
                break;
            default:
                iconEl.className = 'inline-flex items-center justify-center w-20 h-20 rounded-full mx-auto mb-4 bg-red-100';
                iconEl.innerHTML = '<i class="fas fa-times-circle text-4xl text-red-600"></i>';
        }

        // 显示弹窗
        modal.classList.remove('hidden');

        // 添加动画效果
        const modalContent = modal.querySelector('div:nth-child(2)');
        modalContent.classList.add('scale-100', 'opacity-100');
        setTimeout(() => {
            modalContent.classList.remove('scale-95', 'opacity-0');
        }, 10);

        // 设置倒计时
        let countdown = 5;
        const updateTimer = () => {
            timerEl.textContent = `${countdown}秒后自动跳转至登录页面...`;
            if (countdown <= 0) {
                clearInterval(timer);
                // 清除会话存储
                Api.clearAuthSession();
                // 跳转到登录页
                window.location.href = '/login.html';
            }
            countdown--;
        };

        // 开始倒计时
        updateTimer();
        const timer = setInterval(updateTimer, 1000);

        // 点击登录按钮
        loginBtn.onclick = () => {
            clearInterval(timer);
            // 清除会话存储
            Api.clearAuthSession();
            // 跳转到登录页
            window.location.href = '/login.html';
        };
    }

    // 暴露给window以便API.js可以调用
    window.showMessage = showMessage;
    window.showAuthModal = showAuthModal;

    // 创建一个全局工具提示元素
    const tooltip = document.createElement('div');
    tooltip.className = 'filename-tooltip';
    document.body.appendChild(tooltip);
    
    // 全局委托事件处理器，处理文件名和描述的鼠标悬停
    document.addEventListener('mouseover', function(e) {
        // 查找最近的带有title属性的元素
        const target = e.target.closest('[title]');
        if (target && target.classList.contains('truncate')) {
            const text = target.getAttribute('title');
            if (text && text !== '无描述') {
                // 计算位置，显示在元素下方
                const rect = target.getBoundingClientRect();
                tooltip.textContent = text;
                tooltip.style.left = rect.left + 'px';
                tooltip.style.top = (rect.bottom + 10) + 'px';
                tooltip.style.opacity = '1';
                
                // 防止工具提示超出视口
                const tooltipRect = tooltip.getBoundingClientRect();
                if (tooltipRect.right > window.innerWidth) {
                    tooltip.style.left = (window.innerWidth - tooltipRect.width - 10) + 'px';
                }
            }
        }
    });
    
    document.addEventListener('mouseout', function(e) {
        if (e.target.closest('[title]')) {
            tooltip.style.opacity = '0';
        }
    });

    // 个人资料弹窗功能
    const userProfileBtn = document.getElementById('userProfileBtn');
    const userProfileModal = document.getElementById('userProfileModal');
    const closeProfileModal = document.getElementById('closeProfileModal');
    const profileAvatar = document.getElementById('profileAvatar');
    const profileName = document.getElementById('profileName');
    const profileRole = document.getElementById('profileRole');
    const profileAccountId = document.getElementById('profileAccountId');
    const profileRegTime = document.getElementById('profileRegTime');
    const profileLastLogin = document.getElementById('profileLastLogin');

    if (userProfileBtn && userProfileModal) {
        // 点击个人资料按钮显示弹窗
        userProfileBtn.addEventListener('click', (e) => {
            e.preventDefault();
            
            // 关闭下拉菜单
            if (userDropdown) {
                userDropdown.classList.add('hidden');
            }
            
            // 获取当前用户信息
            const fullName = sessionStorage.getItem('userFullName') || '未知用户';
            let role = sessionStorage.getItem('userRole') || 'ROLE_USER';
            
            // 格式化角色显示
            if (role === 'ROLE_ADMIN') {
                role = '系统管理员';
            } else if (role === 'ROLE_USER') {
                role = '普通用户';
            }
            
            // 填充个人资料信息
            if (profileAvatar) {
                profileAvatar.textContent = fullName.charAt(0).toUpperCase();
            }
            
            if (profileName) {
                profileName.textContent = fullName;
            }
            
            if (profileRole) {
                profileRole.textContent = role;
            }
            
            // 账号ID使用随机ID (实际应从API获取)
            if (profileAccountId) {
                const userId = sessionStorage.getItem('userId') || ('USER_' + Math.floor(Math.random() * 10000));
                profileAccountId.textContent = userId;
            }
            
            // 设置模拟的注册时间和最后登录时间
            if (profileRegTime) {
                const regDate = new Date();
                regDate.setMonth(regDate.getMonth() - 3); // 假设3个月前注册
                profileRegTime.textContent = regDate.toLocaleString('zh-CN');
            }
            
            if (profileLastLogin) {
                const loginDate = new Date();
                profileLastLogin.textContent = loginDate.toLocaleString('zh-CN');
            }
            
            // 显示弹窗
            userProfileModal.classList.remove('hidden');
        });
        
        // 关闭弹窗按钮
        if (closeProfileModal) {
            closeProfileModal.addEventListener('click', () => {
                userProfileModal.classList.add('hidden');
            });
        }
        
        // 点击弹窗外部区域关闭
        userProfileModal.addEventListener('click', (e) => {
            if (e.target === userProfileModal) {
                userProfileModal.classList.add('hidden');
            }
        });
    }

    // 显示物料内容的函数
    function showMaterialContent() {
        // 隐藏仪表盘内容
        const dashboardContent = document.getElementById('dashboardContent');
        if (dashboardContent) {
            dashboardContent.classList.add('hidden');
        }
        
        // 显示物料内容
        const materialsContent = document.getElementById('materialsContent');
        if (materialsContent) {
            materialsContent.classList.remove('hidden');
        }
        
        // 更新菜单状态
        const materialsBtn = document.getElementById('materialsBtn');
        if (materialsBtn) {
            // 移除所有菜单项的激活状态
            const allMenuItems = document.querySelectorAll('.menu-item, .submenu-item');
            allMenuItems.forEach(i => i.classList.remove('active'));
            // 添加激活状态到物料菜单
            materialsBtn.classList.add('active');
        }
        
        // 加载物料数据
        loadMaterials();
    }

    // 显示上传模态框
    function showUploadModal() {
        const uploadMaterialModal = document.getElementById('uploadMaterialModal');
        if (uploadMaterialModal) {
            uploadMaterialModal.classList.remove('hidden');
        }
    }

    // 添加返回首页功能
    document.addEventListener('DOMContentLoaded', function() {
        const backToDashboardBtn = document.getElementById('backToDashboardBtn');
        if (backToDashboardBtn) {
            backToDashboardBtn.addEventListener('click', function() {
                // 隐藏物料内容
                const materialsContent = document.getElementById('materialsContent');
                if (materialsContent) {
                    materialsContent.classList.add('hidden');
                }
                
                // 显示仪表盘内容
                const dashboardContent = document.getElementById('dashboardContent');
                if (dashboardContent) {
                    dashboardContent.classList.remove('hidden');
                }
                
                // 更新菜单激活状态
                const materialsBtn = document.getElementById('materialsBtn');
                if (materialsBtn) {
                    materialsBtn.classList.remove('active');
                }
            });
        }
    });

    // 公告列表功能
    const viewAllNoticesBtn = document.getElementById('viewAllNoticesBtn');
    const addNoticeBtn = document.getElementById('addNoticeBtn');
    const noticesList = document.getElementById('noticesList');
    const noticesLoading = document.getElementById('noticesLoading');
    const noNotices = document.getElementById('noNotices');
    
    // 添加查看全部公告相关变量
    const allNoticesModal = document.getElementById('allNoticesModal');
    const closeAllNoticesBtn = document.getElementById('closeAllNoticesBtn');
    const allNoticesList = document.getElementById('allNoticesList');
    const allNoticesLoading = document.getElementById('allNoticesLoading');
    const noticesPagination = document.getElementById('noticesPagination');
    const prevPageBtn = document.getElementById('prevPageBtn');
    const nextPageBtn = document.getElementById('nextPageBtn');
    const currentPageSpan = document.getElementById('currentPage');
    const totalPagesSpan = document.getElementById('totalPages');
    
    // 分页配置
    let currentPage = 1;
    const itemsPerPage = 10; // 确保每页显示10条公告
    let allNoticesData = [];

    if (viewAllNoticesBtn && addNoticeBtn && noticesList && noticesLoading && noNotices) {
        // 修改查看全部点击事件，显示公告列表弹窗
        viewAllNoticesBtn.addEventListener('click', (e) => {
            e.preventDefault();
            
            // 显示公告列表弹窗
            if (allNoticesModal) {
                allNoticesModal.classList.remove('hidden');
                
                // 加载所有公告数据
                loadAllNotices();
            }
        });

        addNoticeBtn.addEventListener('click', () => {
            // 显示添加公告弹窗
            addNoticeModal.classList.remove('hidden');
        });

        // 加载公告数据（首页显示）
        loadNotices();
    }
    
    // 全部公告弹窗相关事件
    if (closeAllNoticesBtn) {
        closeAllNoticesBtn.addEventListener('click', () => {
            allNoticesModal.classList.add('hidden');
        });
    }
    
    // 分页控制
    if (prevPageBtn && nextPageBtn) {
        prevPageBtn.addEventListener('click', () => {
            if (currentPage > 1) {
                currentPage--;
                renderNoticesPage();
            }
        });
        
        nextPageBtn.addEventListener('click', () => {
            const totalPages = Math.ceil(allNoticesData.length / itemsPerPage);
            if (currentPage < totalPages) {
                currentPage++;
                renderNoticesPage();
            }
        });
    }

    // 加载公告数据
    async function loadNotices() {
        const noticesList = document.getElementById('noticesList');
        const noticesLoading = document.getElementById('noticesLoading');
        const noNotices = document.getElementById('noNotices');
        
        if (!noticesList || !noticesLoading || !noNotices) return;
        
        try {
            // 显示加载状态
            noticesLoading.classList.remove('hidden');
            noticesList.innerHTML = '';
            
            // 尝试加载公告数据
            const notices = await Api.getNotices();
            
            // 隐藏加载状态
            noticesLoading.classList.add('hidden');
            
            if (notices && notices.length > 0) {
                // 有数据，显示公告
                noNotices.classList.add('hidden');
                
                // 显示最新的三条公告
                const recentNotices = notices.slice(0, 3);
                
                // 获取当前用户的角色
                const isAdmin = Api.isAdmin();
                
                // 获取所有公告的已读状态(普通用户才需要)
                let readStatusMap = {};
                if (!isAdmin) {
                    // 优先使用全局状态映射
                    if (window.readStatusMap) {
                        readStatusMap = window.readStatusMap;
                    }
                    
                    // 如果有全局已读公告IDs，确保它们被标记为已读
                    if (window.readNoticeIds && window.readNoticeIds.size > 0) {
                        for (const notice of recentNotices) {
                            if (window.readNoticeIds.has(notice.id)) {
                                readStatusMap[notice.id] = true;
                            }
                        }
                    }
                    
                    // 为每个公告检查已读状态（仅检查全局状态中不存在的）
                    for (const notice of recentNotices) {
                        if (readStatusMap[notice.id] === undefined) {
                            readStatusMap[notice.id] = await Api.checkNoticeRead(notice.id);
                            // 如果已读，也添加到全局已读ID集合中
                            if (readStatusMap[notice.id] && !window.readNoticeIds) {
                                window.readNoticeIds = new Set();
                                window.readNoticeIds.add(notice.id);
                            } else if (readStatusMap[notice.id] && window.readNoticeIds) {
                                window.readNoticeIds.add(notice.id);
                            }
                        }
                    }
                    
                    // 更新全局状态
                    window.readStatusMap = {...window.readStatusMap, ...readStatusMap};
                }
                
                recentNotices.forEach(notice => {
                    // 根据公告类型设置不同的背景颜色
                    let bgColor = 'bg-blue-50';
                    let borderColor = 'border-blue-500';
                    
                    switch (notice.type) {
                        case 'important':
                            bgColor = 'bg-red-50';
                            borderColor = 'border-red-500';
                            break;
                        case 'warning':
                            bgColor = 'bg-yellow-50';
                            borderColor = 'border-yellow-500';
                            break;
                        case 'info':
                            bgColor = 'bg-green-50';
                            borderColor = 'border-green-500';
                            break;
                    }
                    
                    // 格式化日期
                    const publishDate = new Date(notice.publishTime);
                    // 直接显示具体时间，不再使用相对时间
                    const timeText = publishDate.toLocaleString('zh-CN');
                    
                    // 创建公告元素
                    const noticeElement = document.createElement('div');
                    noticeElement.className = `p-4 ${bgColor} border-l-4 ${borderColor} rounded hover:shadow-md transition-shadow cursor-pointer notice-item`;
                    noticeElement.dataset.id = notice.id;
                    
                    // 根据已读状态添加不同的UI元素（只对普通用户显示）
                    let readStatusHTML = '';
                    if (!isAdmin) {
                        if (readStatusMap[notice.id]) {
                            readStatusHTML = '<span class="text-xs px-2 py-0.5 bg-green-100 text-green-700 rounded-full ml-2">已读</span>';
                        } else {
                            readStatusHTML = '<span class="text-xs px-2 py-0.5 bg-red-100 text-red-700 rounded-full ml-2">未读</span>';
                        }
                    }
                    
                    noticeElement.innerHTML = `
                        <div class="flex justify-between">
                            <h4 class="text-sm font-semibold text-gray-800 flex items-center">
                                ${notice.title}
                                ${readStatusHTML}
                            </h4>
                            <span class="text-xs text-gray-500">${timeText}</span>
                        </div>
                        <p class="text-sm text-gray-600 mt-1">${notice.content}</p>
                    `;
                    
                    // 添加点击事件，查看公告详情
                    noticeElement.addEventListener('click', () => {
                        viewNoticeDetails(notice);
                    });
                    
                    // 添加到公告列表
                    noticesList.appendChild(noticeElement);
                });
            } else {
                // 无数据，显示空状态
                noNotices.classList.remove('hidden');
            }
        } catch (error) {
            console.error('加载公告数据出错:', error);
            noticesLoading.classList.add('hidden');
            
            // 显示错误提示
            noticesList.innerHTML = `
                <div class="p-4 bg-red-50 border-l-4 border-red-500 rounded">
                    <div class="flex items-center">
                        <i class="fas fa-exclamation-circle text-red-500 mr-2"></i>
                        <p class="text-sm text-gray-700">加载公告失败，请刷新页面重试</p>
                    </div>
                </div>
            `;
        }
    }
    
    // 查看公告详情
    function viewNoticeDetails(notice) {
        // 记录当前查看的公告ID
        window.currentViewingNoticeId = notice.id;
        const viewNoticeModal = document.getElementById('viewNoticeModal');
        const viewNoticeTitle = document.getElementById('viewNoticeTitle');
        const viewNoticeContent = document.getElementById('viewNoticeContent');
        const viewNoticeTime = document.getElementById('viewNoticeTime');
        const viewNoticeAuthor = document.getElementById('viewNoticeAuthor');
        const viewNoticeType = document.getElementById('viewNoticeType');
        const noticeAdminControls = document.getElementById('noticeAdminControls');
        const closeViewNoticeBtn = document.getElementById('closeViewNoticeBtn');
        const editNoticeBtn = document.getElementById('editNoticeBtn');
        const deleteNoticeBtn = document.getElementById('deleteNoticeBtn');
        const allNoticesModal = document.getElementById('allNoticesModal');
        
        // 已读相关元素
        const readStatus = document.getElementById('readStatus');
        const markAsReadBtn = document.getElementById('markAsReadBtn');
        const readUsersList = document.getElementById('readUsersList');
        const readUsersLoading = document.getElementById('readUsersLoading');
        const noReadUsers = document.getElementById('noReadUsers');
        const readCount = document.getElementById('readCount');
        
        if (!viewNoticeModal || !viewNoticeTitle || !viewNoticeContent) return;
        
        // 首先关闭全部公告弹窗
        if (allNoticesModal) {
            allNoticesModal.classList.add('hidden');
        }
        
        // 设置公告详情
        viewNoticeTitle.textContent = notice.title;
        viewNoticeContent.innerHTML = notice.content.replace(/\n/g, '<br>');
        
        // 设置公告类型标签样式
        if (viewNoticeType) {
            let typeText = '普通公告';
            let typeClass = 'bg-blue-100 text-blue-700';
            
            switch (notice.type) {
                case 'important':
                    typeText = '重要公告';
                    typeClass = 'bg-red-100 text-red-700';
                    break;
                case 'warning':
                    typeText = '警告公告';
                    typeClass = 'bg-yellow-100 text-yellow-700';
                    break;
                case 'info':
                    typeText = '信息公告';
                    typeClass = 'bg-green-100 text-green-700';
                    break;
            }
            
            viewNoticeType.textContent = typeText;
            viewNoticeType.className = `ml-3 text-xs px-2 py-1 rounded-full font-medium ${typeClass}`;
        }
        
        if (viewNoticeTime) {
            viewNoticeTime.textContent = `发布时间：${new Date(notice.publishTime).toLocaleString('zh-CN')}`;
        }
        
        if (viewNoticeAuthor) {
            viewNoticeAuthor.textContent = `发布者：${notice.publishUser || '管理员'}`;
        }
        
        // 根据用户角色显示或隐藏管理控件
        if (noticeAdminControls) {
            const isAdmin = Api.isAdmin();
            
            if (isAdmin) {
                noticeAdminControls.classList.remove('hidden');
                
                // 设置编辑按钮点击事件
                if (editNoticeBtn) {
                    // 存储当前公告ID
                    editNoticeBtn.dataset.id = notice.id;
                    
                    // 点击编辑按钮时打开编辑弹窗
                    editNoticeBtn.onclick = () => {
                        openEditNoticeModal(notice);
                        viewNoticeModal.classList.add('hidden');
                    };
                }
                
                // 设置删除按钮点击事件
                if (deleteNoticeBtn) {
                    // 存储当前公告ID
                    deleteNoticeBtn.dataset.id = notice.id;
                    
                    // 点击删除按钮时确认删除
                    deleteNoticeBtn.onclick = async () => {
                        if (confirm('确定要删除此公告吗？此操作不可恢复。')) {
                            try {
                                const result = await Api.deleteNotice(notice.id);
                                
                                if (result && result.success) {
                                    // 关闭详情弹窗
                                    viewNoticeModal.classList.add('hidden');
                                    
                                    // 显示成功提示
                                    showMessage('成功', '公告已成功删除', 'success');
                                    
                                    // 强制刷新页面，确保公告删除效果立即显示
                                    setTimeout(() => {
                                        window.location.reload();
                                    }, 1000); // 延迟1秒，让用户看到成功提示
                                } else {
                                    showMessage('删除失败', result ? result.message : '未知错误', 'error');
                                }
                            } catch (error) {
                                console.error('删除公告出错:', error);
                                showMessage('删除失败', '请稍后重试', 'error');
                            }
                        }
                    };
                }
            } else {
                noticeAdminControls.classList.add('hidden');
            }
        }
        
        // 处理已读状态 - 修改为自动标记为已读
        if (readStatus && markAsReadBtn) {
            // 默认隐藏已读状态和标记为已读按钮
            readStatus.classList.add('hidden');
            markAsReadBtn.classList.add('hidden');
            
            // 检查当前用户是否已读
            Api.checkNoticeRead(notice.id).then(hasRead => {
                if (hasRead) {
                    // 用户已读此公告
                    readStatus.classList.remove('hidden');
                    
                    // 确保内存中的状态也是最新的
                    // 确保存在全局状态映射
                    if (!window.readStatusMap) {
                        window.readStatusMap = {};
                    }
                    window.readStatusMap[notice.id] = true;
                    
                    // 同时更新当前函数域中的状态
                    if (typeof readStatusMap !== 'undefined') {
                        readStatusMap[notice.id] = true;
                    }
                } else {
                    // 用户未读此公告，自动标记为已读
                    Api.markNoticeAsRead(notice.id).then(result => {
                        if (result && result.success) {
                            // 标记成功
                            readStatus.classList.remove('hidden');
                            
                            // 重新加载已读人员列表
                            loadNoticeReadUsers(notice.id);
                            
                            // 重新加载未读人员列表（仅管理员可见）
                            loadNoticeUnreadUsers(notice.id);
                            
                            // 确保存在全局状态映射
                            if (!window.readStatusMap) {
                                window.readStatusMap = {};
                            }
                            window.readStatusMap[notice.id] = true;
                            
                            // 同时更新当前函数域中的状态
                            if (typeof readStatusMap !== 'undefined') {
                                readStatusMap[notice.id] = true;
                            }
                                
                            // 直接刷新此公告的已读状态
                            directRefreshNoticeStatus(notice.id);
                            
                            // 确保当前模态框内的已读状态也更新
                            const inModalReadStatus = document.getElementById('readStatus');
                            if (inModalReadStatus) {
                                inModalReadStatus.classList.remove('hidden');
                            }
                        } else {
                            console.error('标记公告已读失败:', result ? result.message : '未知错误');
                        }
                    }).catch(error => {
                        console.error('标记公告已读出错:', error);
                    });
                }
            });
        }
        
        // 加载已读人员列表
        if (readUsersList && readUsersLoading && noReadUsers && readCount) {
            loadNoticeReadUsers(notice.id);
        }
        
        // 加载未读人员列表（仅管理员可见）
        loadNoticeUnreadUsers(notice.id);
        
        // 设置关闭按钮点击事件
        if (closeViewNoticeBtn) {
            closeViewNoticeBtn.onclick = () => {
                viewNoticeModal.classList.add('hidden');
                // 当关闭模态框时，如果有公告ID被记录，则刷新它的状态
                if (window.currentViewingNoticeId) {
                    directRefreshNoticeStatus(window.currentViewingNoticeId);
                }
            };
        }
        
        // 点击蒙层关闭弹窗
        viewNoticeModal.onclick = (e) => {
            if (e.target === viewNoticeModal) {
                viewNoticeModal.classList.add('hidden');
                // 当关闭模态框时，如果有公告ID被记录，则刷新它的状态
                if (window.currentViewingNoticeId) {
                    directRefreshNoticeStatus(window.currentViewingNoticeId);
                }
            }
        };
        
        // 显示弹窗
        viewNoticeModal.classList.remove('hidden');
    }
    
    // 打开编辑公告弹窗
    function openEditNoticeModal(notice) {
        const addNoticeModal = document.getElementById('addNoticeModal');
        const noticeForm = document.getElementById('noticeForm');
        const noticeModalTitle = document.getElementById('noticeModalTitle');
        const noticeIdInput = document.getElementById('noticeId');
        const noticeTitleInput = document.getElementById('noticeTitle');
        const noticeContentInput = document.getElementById('noticeContent');
        const noticeTypeSelect = document.getElementById('noticeType');
        const submitNoticeBtn = document.getElementById('submitNoticeBtn');
        
        if (!addNoticeModal || !noticeForm || !noticeModalTitle || !noticeTitleInput || !noticeContentInput || !noticeTypeSelect || !submitNoticeBtn) return;
        
        // 设置表单标题
        noticeModalTitle.textContent = '编辑系统公告';
        
        // 设置表单数据
        noticeIdInput.value = notice.id;
        noticeTitleInput.value = notice.title;
        noticeContentInput.value = notice.content;
        noticeTypeSelect.value = notice.type || 'normal';
        
        // 修改提交按钮文本
        submitNoticeBtn.textContent = '保存修改';
        
        // 显示弹窗
        addNoticeModal.classList.remove('hidden');
    }

    // 编辑公告功能
    const editNoticeBtn = document.getElementById('editNoticeBtn');
    const editNoticeModal = document.getElementById('editNoticeModal');
    const closeEditNoticeBtn = document.getElementById('closeEditNoticeBtn');
    const noticeTitleInput = document.getElementById('noticeTitle');
    const noticeContentInput = document.getElementById('noticeContent');
    const noticeTypeSelect = document.getElementById('noticeType');
    const noticeIdInput = document.getElementById('noticeId');

    if (editNoticeBtn && editNoticeModal && closeEditNoticeBtn && noticeTitleInput && noticeContentInput && noticeTypeSelect && noticeIdInput) {
        editNoticeBtn.addEventListener('click', () => {
            // 显示编辑公告弹窗
            editNoticeModal.classList.remove('hidden');
            // 加载公告数据
            loadNotice(noticeIdInput.value);
        });

        closeEditNoticeBtn.addEventListener('click', () => {
            // 关闭编辑公告弹窗
            editNoticeModal.classList.add('hidden');
        });

        // 提交编辑公告
        editNoticeForm.addEventListener('submit', async (e) => {
            e.preventDefault();

            const noticeId = noticeIdInput.value;
            const title = noticeTitleInput.value;
            const content = noticeContentInput.value;
            const type = noticeTypeSelect.value;

            try {
                const result = await Api.updateNotice(noticeId, title, content, type);

                if (result && result.success) {
                    // 关闭编辑公告弹窗
                    editNoticeModal.classList.add('hidden');
                    // 重新加载公告列表
                    loadNotices();
                    // 显示成功提示
                    showMessage('成功', '公告已成功更新', 'success');
                } else {
                    showMessage('更新失败', result ? result.message : '未知错误', 'error');
                }
            } catch (error) {
                console.error('更新公告出错:', error);
                showMessage('更新失败', '请稍后重试', 'error');
            }
        });
    }

    // 发布公告功能
    const submitNoticeBtn = document.getElementById('submitNoticeBtn');
    const cancelNoticeBtn = document.getElementById('cancelNoticeBtn');
    const noticeForm = document.getElementById('noticeForm');

    if (submitNoticeBtn && cancelNoticeBtn && noticeForm) {
        // 将事件监听器绑定到表单的submit事件，而不是按钮的click事件
        noticeForm.addEventListener('submit', async (e) => {
            e.preventDefault();

            const noticeIdInput = document.getElementById('noticeId');
            const noticeTitleInput = document.getElementById('noticeTitle');
            const noticeContentInput = document.getElementById('noticeContent');
            const noticeTypeSelect = document.getElementById('noticeType');
            
            const noticeId = noticeIdInput.value;
            const title = noticeTitleInput.value;
            const content = noticeContentInput.value;
            const type = noticeTypeSelect.value;

            try {
                // 禁用提交按钮，防止重复提交
                submitNoticeBtn.disabled = true;
                submitNoticeBtn.innerHTML = '<i class="fas fa-spinner fa-spin mr-2"></i>' + (noticeId ? '更新中...' : '发布中...');
                
                let result;
                
                // 根据是否有公告ID决定是更新还是添加
                if (noticeId) {
                    // 更新现有公告
                    result = await Api.updateNotice(noticeId, title, content, type);
                } else {
                    // 添加新公告
                    result = await Api.addNotice(title, content, type);
                }

                if (result && result.success) {
                    // 清空表单
                    noticeForm.reset();
                    
                    // 关闭添加公告弹窗
                    addNoticeModal.classList.add('hidden');
                    
                    // 显示成功提示
                    showMessage('成功', noticeId ? '公告已成功更新' : '公告已成功发布', 'success');
                    
                    // 强制刷新页面，确保公告更改立即显示
                    setTimeout(() => {
                        window.location.reload();
                    }, 1000); // 延迟1秒，让用户看到成功提示
                } else {
                    showMessage(noticeId ? '更新失败' : '发布失败', result ? result.message : '未知错误', 'error');
                }
            } catch (error) {
                console.error(noticeId ? '更新公告出错:' : '发布公告出错:', error);
                showMessage(noticeId ? '更新失败' : '发布失败', '请稍后重试', 'error');
            } finally {
                // 恢复提交按钮状态
                submitNoticeBtn.disabled = false;
                submitNoticeBtn.innerHTML = noticeId ? '保存修改' : '发布公告';
            }
        });

        cancelNoticeBtn.addEventListener('click', () => {
            // 关闭添加公告弹窗
            addNoticeModal.classList.add('hidden');
        });
    }

    // 添加查看全部公告功能
    
    if (viewAllNoticesBtn && allNoticesModal) {
        // 移除之前的点击事件监听器
        viewAllNoticesBtn.removeEventListener('click', () => {});
        
        // 添加新的点击事件监听器
        viewAllNoticesBtn.addEventListener('click', (e) => {
            e.preventDefault();
            
            // 显示公告列表弹窗
            allNoticesModal.classList.remove('hidden');
            
            // 加载所有公告数据
            loadAllNotices();
        });
        
        if (closeAllNoticesBtn) {
            closeAllNoticesBtn.addEventListener('click', () => {
                allNoticesModal.classList.add('hidden');
            });
        }
        
        // 分页控制
        if (prevPageBtn && nextPageBtn) {
            prevPageBtn.addEventListener('click', () => {
                if (currentPage > 1) {
                    currentPage--;
                    renderNoticesPage();
                }
            });
            
            nextPageBtn.addEventListener('click', () => {
                const totalPages = Math.ceil(allNoticesData.length / itemsPerPage);
                if (currentPage < totalPages) {
                    currentPage++;
                    renderNoticesPage();
                }
            });
        }
    }
    
    // 加载所有公告数据
    async function loadAllNotices() {
        try {
            if (allNoticesLoading) {
                allNoticesLoading.classList.remove('hidden');
            }
            
            // 清空列表
            if (allNoticesList) {
                allNoticesList.innerHTML = '';
                if (allNoticesLoading) {
                    allNoticesList.appendChild(allNoticesLoading);
                }
            }
            
            // 重置分页
            currentPage = 1;
            
            // 获取所有公告
            const notices = await Api.getNotices();
            allNoticesData = notices || [];
            
            // 对公告按发布时间从新到旧排序
            allNoticesData.sort((a, b) => new Date(b.publishTime) - new Date(a.publishTime));
            
            // 隐藏加载状态
            if (allNoticesLoading) {
                allNoticesLoading.classList.add('hidden');
            }
            
            // 渲染第一页
            renderNoticesPage();
            
        } catch (error) {
            console.error('加载公告列表出错:', error);
            
            if (allNoticesLoading) {
                allNoticesLoading.classList.add('hidden');
            }
            
            if (allNoticesList) {
                allNoticesList.innerHTML = `
                    <div class="p-4 bg-red-50 border-l-4 border-red-500 rounded">
                        <div class="flex items-center">
                            <i class="fas fa-exclamation-circle text-red-500 mr-2"></i>
                            <p class="text-sm text-gray-700">加载公告失败，请刷新页面重试</p>
                        </div>
                    </div>
                `;
            }
        }
    }
    
    // 渲染分页公告数据
    async function renderNoticesPage() {
        if (!allNoticesList) return;
        
        // 清空列表
        allNoticesList.innerHTML = '';
        
        // 计算总页数
        const totalPages = Math.ceil(allNoticesData.length / itemsPerPage);
        
        if (allNoticesData.length === 0) {
            // 无数据
            allNoticesList.innerHTML = `
                <div class="py-10 flex flex-col items-center">
                    <div class="w-16 h-16 bg-gray-100 rounded-full flex items-center justify-center mb-3">
                        <i class="fas fa-bullhorn text-gray-400 text-xl"></i>
                    </div>
                    <p class="text-gray-500 mb-2">暂无系统公告</p>
                    <p class="text-sm text-gray-400">管理员发布的公告将显示在这里</p>
                </div>
            `;
            
            // 隐藏分页
            if (noticesPagination) {
                noticesPagination.classList.add('hidden');
            }
            
            return;
        }
        
        // 显示分页
        if (noticesPagination) {
            if (totalPages > 1) {
                noticesPagination.classList.remove('hidden');
            } else {
                noticesPagination.classList.add('hidden');
            }
            
            // 更新页码显示
            if (currentPageSpan) currentPageSpan.textContent = currentPage;
            if (totalPagesSpan) totalPagesSpan.textContent = totalPages;
            
            // 更新按钮状态
            if (prevPageBtn) prevPageBtn.disabled = currentPage === 1;
            if (nextPageBtn) nextPageBtn.disabled = currentPage === totalPages;
        }
        
        // 计算当前页的数据
        const startIndex = (currentPage - 1) * itemsPerPage;
        const endIndex = Math.min(startIndex + itemsPerPage, allNoticesData.length);
        const pageItems = allNoticesData.slice(startIndex, endIndex);
        
        // 获取当前用户的角色
        const isAdmin = Api.isAdmin();
        
        // 获取所有公告的已读状态(普通用户才需要)
        let readStatusMap = {};
        if (!isAdmin) {
            // 优先使用全局状态映射
            if (window.readStatusMap) {
                readStatusMap = window.readStatusMap;
            }
            
            // 如果有全局已读公告IDs，确保它们被标记为已读
            if (window.readNoticeIds && window.readNoticeIds.size > 0) {
                for (const notice of pageItems) {
                    if (window.readNoticeIds.has(notice.id)) {
                        readStatusMap[notice.id] = true;
                    }
                }
            }
            
            // 为每个公告检查已读状态（仅检查全局状态中不存在的）
            for (const notice of pageItems) {
                if (readStatusMap[notice.id] === undefined) {
                    readStatusMap[notice.id] = await Api.checkNoticeRead(notice.id);
                    // 如果已读，也添加到全局已读ID集合中
                    if (readStatusMap[notice.id] && !window.readNoticeIds) {
                        window.readNoticeIds = new Set();
                        window.readNoticeIds.add(notice.id);
                    } else if (readStatusMap[notice.id] && window.readNoticeIds) {
                        window.readNoticeIds.add(notice.id);
                    }
                }
            }
            
            // 更新全局状态
            window.readStatusMap = {...window.readStatusMap, ...readStatusMap};
        }
        
        // 创建每个公告项
        pageItems.forEach(notice => {
            // 根据公告类型设置不同的颜色
            let bgColor = 'bg-blue-50';
            let borderColor = 'border-blue-500';
            
            switch (notice.type) {
                case 'important':
                    bgColor = 'bg-red-50';
                    borderColor = 'border-red-500';
                    break;
                case 'warning':
                    bgColor = 'bg-yellow-50';
                    borderColor = 'border-yellow-500';
                    break;
                case 'info':
                    bgColor = 'bg-green-50';
                    borderColor = 'border-green-500';
                    break;
            }
            
            // 格式化发布时间
            const publishTime = new Date(notice.publishTime).toLocaleString('zh-CN');
            
            // 截断过长的内容
            const maxContentLength = 100;
            let displayContent = notice.content;
            if (displayContent.length > maxContentLength) {
                displayContent = displayContent.substring(0, maxContentLength) + '...';
            }
            
            // 根据已读状态添加不同的UI元素（只对普通用户显示）
            let readStatusHTML = '';
            if (!isAdmin) {
                if (readStatusMap[notice.id]) {
                    readStatusHTML = '<span class="text-xs px-2 py-0.5 bg-green-100 text-green-700 rounded-full ml-2">已读</span>';
                } else {
                    readStatusHTML = '<span class="text-xs px-2 py-0.5 bg-red-100 text-red-700 rounded-full ml-2">未读</span>';
                }
            }
            
            // 创建公告元素
            const noticeElement = document.createElement('div');
            noticeElement.className = `p-4 ${bgColor} border-l-4 ${borderColor} rounded hover:shadow-md transition-shadow cursor-pointer mb-3`;
            noticeElement.dataset.id = notice.id;
            
            noticeElement.innerHTML = `
                <div class="flex justify-between items-start">
                    <h4 class="font-semibold text-gray-800 flex items-center">
                        ${notice.title}
                        ${readStatusHTML}
                    </h4>
                    <span class="text-xs text-gray-500 ml-2">${publishTime}</span>
                </div>
                <p class="text-gray-600 mt-2">${displayContent.replace(/\n/g, '<br>')}</p>
                <div class="mt-2 text-xs text-gray-500">
                    发布者：${notice.publishUser || '管理员'}
                </div>
            `;
            
            // 添加点击事件，查看公告详情
            noticeElement.addEventListener('click', () => {
                viewNoticeDetails(notice);
            });
            
            // 添加到公告列表
            allNoticesList.appendChild(noticeElement);
        });
    }

    // 显示仪表盘页面内容
    async function showDashboard() {
        // 切换页面内容
        const materialsContent = document.getElementById('materialsContent');
    }

    // 初始化上传表单
    function initUploadForm() {
        // 检查必要的DOM元素是否存在
        if (!uploadMaterialForm || !materialFile || !fileDropZone || !selectedFile) {
            console.log('上传表单初始化：部分DOM元素不存在');
            return;
        }
        
        // 设置文件拖放区域事件
        fileDropZone.addEventListener('dragover', (e) => {
            e.preventDefault();
            fileDropZone.classList.add('bg-blue-50', 'border-blue-300');
        });

        fileDropZone.addEventListener('dragleave', () => {
            fileDropZone.classList.remove('bg-blue-50', 'border-blue-300');
        });

        fileDropZone.addEventListener('drop', (e) => {
            e.preventDefault();
            fileDropZone.classList.remove('bg-blue-50', 'border-blue-300');

            if (e.dataTransfer.files.length) {
                handleFileSelection(e.dataTransfer.files[0]);
                // 同步 input[type=file] 的 files
                const dataTransfer = new DataTransfer();
                dataTransfer.items.add(e.dataTransfer.files[0]);
                materialFile.files = dataTransfer.files;
            }
        });
        
        // 点击拖放区域触发文件选择
        fileDropZone.addEventListener('click', () => {
            materialFile.click();
        });
        
        // 文件选择变更事件
        materialFile.addEventListener('change', (e) => {
            if (e.target.files.length) {
                handleFileSelection(e.target.files[0]);
            }
        });
        
        // 移除选中文件按钮事件
        if (removeSelectedFile) {
            removeSelectedFile.addEventListener('click', () => {
                resetUploadForm();
            });
        }
        
        console.log('上传表单初始化完成');
    }

    // 加载公告已读人员列表
    async function loadNoticeReadUsers(noticeId) {
        const readUsersList = document.getElementById('readUsersList');
        const readUsersLoading = document.getElementById('readUsersLoading');
        const noReadUsers = document.getElementById('noReadUsers');
        const readCount = document.getElementById('readCount');
        
        if (!readUsersList || !readUsersLoading || !noReadUsers || !readCount) return;
        
        // 显示加载状态
        readUsersLoading.classList.remove('hidden');
        noReadUsers.classList.add('hidden');
        
        // 清空已有内容（除了加载状态和无数据提示）
        Array.from(readUsersList.children).forEach(child => {
            if (child !== readUsersLoading && child !== noReadUsers) {
                readUsersList.removeChild(child);
            }
        });
        
        try {
            // 获取已读记录
            const records = await Api.getNoticeReadRecords(noticeId);
            
            // 隐藏加载状态
            readUsersLoading.classList.add('hidden');
            
            // 更新已读人数
            readCount.textContent = `${records.length}人已读`;
            
            if (records.length === 0) {
                // 无已读记录
                noReadUsers.classList.remove('hidden');
                return;
            }
            
            // 渲染已读人员列表
            records.forEach(record => {
                const userItem = document.createElement('div');
                userItem.className = 'flex justify-between items-center py-1.5 border-b border-gray-100 last:border-0';
                
                // 格式化阅读时间
                const readTime = new Date(record.readTime).toLocaleString('zh-CN');
                
                userItem.innerHTML = `
                    <div class="flex items-center">
                        <div class="w-6 h-6 bg-blue-100 rounded-full flex items-center justify-center text-blue-700 text-xs font-medium mr-2">
                            ${record.userName.charAt(0)}
                        </div>
                        <span class="text-sm text-gray-700">${record.userName}</span>
                    </div>
                    <span class="text-xs text-gray-500">${readTime}</span>
                `;
                
                readUsersList.appendChild(userItem);
            });
        } catch (error) {
            console.error('加载公告已读人员列表出错:', error);
            
            // 隐藏加载状态
            readUsersLoading.classList.add('hidden');
            
            // 显示错误提示
            const errorItem = document.createElement('div');
            errorItem.className = 'py-3 text-center text-sm text-red-500';
            errorItem.innerHTML = '<i class="fas fa-exclamation-circle mr-1"></i>加载已读人员列表失败';
            readUsersList.appendChild(errorItem);
        }
    }

    // 添加刷新公告已读状态的函数
    function refreshNoticeReadStatus() {
        // 获取当前用户的角色，管理员不显示已读状态
        const isAdmin = Api.isAdmin();
        if (isAdmin) return;
        
        // 遍历当前页面上所有的公告元素，并更新状态
        const noticeElements = document.querySelectorAll('[data-id]');
        
        // 创建一个Set保存需要更新的公告ID
        const noticeIdsToUpdate = new Set();
        
        noticeElements.forEach(elem => {
            const noticeId = elem.dataset.id;
            if (noticeId) {
                noticeIdsToUpdate.add(noticeId);
                
                // 更新UI显示
                const statusBadge = elem.querySelector('.text-xs.px-2.py-0.5.rounded-full');
                if (statusBadge) {
                    // 移除旧的未读样式
                    statusBadge.classList.remove('bg-red-100', 'text-red-700', 'bg-blue-100', 'text-blue-700');
                    // 添加已读样式
                    statusBadge.classList.add('bg-green-100', 'text-green-700');
                    // 更新文本
                    statusBadge.textContent = '已读';
                }
            }
        });
        
        // 更新全局readStatusMap中的状态
        if (typeof window.readStatusMap !== 'undefined') {
            noticeIdsToUpdate.forEach(id => {
                window.readStatusMap[id] = true;
            });
        }
        
        // 如果首页公告的readStatusMap存在但和window.readStatusMap不同
        if (typeof readStatusMap !== 'undefined' && readStatusMap !== window.readStatusMap) {
            noticeIdsToUpdate.forEach(id => {
                readStatusMap[id] = true;
            });
        }
    }

    // 添加直接刷新特定公告已读状态的函数
    function directRefreshNoticeStatus(noticeId) {
        // 立即更新所有展示这个公告的元素
        const allNoticeElements = document.querySelectorAll(`[data-id="${noticeId}"]`);
        if (allNoticeElements.length === 0) {
            // 如果找不到元素，就尝试重新加载公告列表
            loadNotices();
            return;
        }
        
        // 更新每个元素的状态
        allNoticeElements.forEach(elem => {
            const statusBadge = elem.querySelector('.text-xs.px-2.py-0.5.rounded-full');
            if (statusBadge) {
                // 移除未读样式
                statusBadge.classList.remove('bg-red-100', 'text-red-700', 'bg-blue-100', 'text-blue-700');
                // 添加已读样式
                statusBadge.classList.add('bg-green-100', 'text-green-700');
                // 更新文本
                statusBadge.textContent = '已读';
            }
        });
        
        // 记录这个公告ID已读
        if (!window.readNoticeIds) {
            window.readNoticeIds = new Set();
        }
        window.readNoticeIds.add(noticeId);
    }

    // 加载公告未读人员列表（仅管理员可见）
    async function loadNoticeUnreadUsers(noticeId) {
        const unreadUsersSection = document.getElementById('unreadUsersSection');
        const unreadUsersList = document.getElementById('unreadUsersList');
        const unreadUsersLoading = document.getElementById('unreadUsersLoading');
        const noUnreadUsers = document.getElementById('noUnreadUsers');
        const unreadCount = document.getElementById('unreadCount');
        
        console.log('开始加载未读人员列表，公告ID:', noticeId);
        console.log('DOM元素检查:', {
            unreadUsersSection: !!unreadUsersSection,
            unreadUsersList: !!unreadUsersList,
            unreadUsersLoading: !!unreadUsersLoading,
            noUnreadUsers: !!noUnreadUsers,
            unreadCount: !!unreadCount
        });
        
        if (!unreadUsersSection || !unreadUsersList || !unreadUsersLoading || !noUnreadUsers || !unreadCount) {
            console.error('未找到必要的DOM元素，无法加载未读人员列表');
            return;
        }
        
        // 检查是否是管理员
        const isAdmin = Api.isAdmin();
        console.log('当前用户是否为管理员:', isAdmin);
        
        if (!isAdmin) {
            unreadUsersSection.classList.add('hidden');
            console.log('非管理员用户，隐藏未读人员列表区域');
            return;
        }
        
        // 显示未读用户区域
        unreadUsersSection.classList.remove('hidden');
        console.log('显示未读用户区域');
        
        // 显示加载状态
        unreadUsersLoading.classList.remove('hidden');
        noUnreadUsers.classList.add('hidden');
        
        // 清空已有内容（除了加载状态和无数据提示）
        Array.from(unreadUsersList.children).forEach(child => {
            if (child !== unreadUsersLoading && child !== noUnreadUsers) {
                unreadUsersList.removeChild(child);
            }
        });
        
        try {
            console.log('开始调用API获取未读记录');
            // 获取未读记录
            const records = await Api.getNoticeUnreadUsers(noticeId);
            console.log('获取到未读记录:', records);
            
            // 隐藏加载状态
            unreadUsersLoading.classList.add('hidden');
            
            // 更新未读人数
            unreadCount.textContent = `${records.length}人未读`;
            console.log('更新未读人数:', records.length);
            
            if (records.length === 0) {
                // 无未读记录
                noUnreadUsers.classList.remove('hidden');
                console.log('无未读记录，显示空状态');
                return;
            }
            
            // 渲染未读人员列表
            console.log('开始渲染未读人员列表');
            records.forEach((user, index) => {
                console.log(`渲染第${index+1}个用户:`, user);
                const userItem = document.createElement('div');
                userItem.className = 'flex justify-between items-center py-1.5 border-b border-gray-100 last:border-0';
                
                // 获取用户名，兼容不同的字段名
                let userName = '未知用户';
                if (user.userName) {
                    userName = user.userName;
                } else if (user.username) {
                    userName = user.username;
                } else if (user.fullName) {
                    userName = user.fullName;
                } else if (user.full_name) {
                    userName = user.full_name;
                }
                
                // 获取用户名首字母
                const userInitial = userName && typeof userName === 'string' ? userName.charAt(0) : '?';
                
                console.log(`用户名: ${userName}, 首字母: ${userInitial}`);
                
                userItem.innerHTML = `
                    <div class="flex items-center">
                        <div class="w-6 h-6 bg-red-100 rounded-full flex items-center justify-center text-red-700 text-xs font-medium mr-2">
                            ${userInitial}
                        </div>
                        <span class="text-sm text-gray-700">${userName}</span>
                    </div>
                    <span class="text-xs bg-yellow-100 text-yellow-700 px-2 py-1 rounded-full">未读</span>
                `;
                
                unreadUsersList.appendChild(userItem);
            });
            console.log('未读人员列表渲染完成');
        } catch (error) {
            console.error('加载公告未读人员列表出错:', error);
            
            // 隐藏加载状态
            unreadUsersLoading.classList.add('hidden');
            
            // 显示错误提示
            const errorItem = document.createElement('div');
            errorItem.className = 'py-3 text-center text-sm text-red-500';
            errorItem.innerHTML = '<i class="fas fa-exclamation-circle mr-1"></i>加载未读人员列表失败';
            unreadUsersList.appendChild(errorItem);
        }
    }
</script>
</body>
</html>
